剪枝之后呢
同一个问题,这个版本放的时候就检查是不是连号,是就不往下走。运行它:
def pruned(n):
st = {"c": 0, "v": 0}
path = []
used = [False] * (n + 1)
def dfs():
st["v"] += 1
if len(path) == n:
st["c"] += 1
return
for x in range(1, n + 1):
if used[x]:
continue
if path and abs(path[-1] - x) == 1:
continue
used[x] = True
path.append(x)
dfs()
path.pop()
used[x] = False
dfs()
return st["c"], st["v"]
print(pruned(5)[1])
全部评论