用python写一个回溯算法
时间: 2024-05-29 19:01:08 浏览: 59
Python 算法集-backtracking.rar
以下是一个用Python编写的回溯算法的示例:
def backtrack(candidates, target):
result = []
path = []
def dfs(start):
if sum(path) == target:
result.append(path[:])
return
for i in range(start, len(candidates)):
if sum(path) + candidates[i] > target:
break
path.append(candidates[i])
dfs(i)
path.pop()
dfs(0)
return result
candidates = [2, 3, 6, 7]
target = 7
print(backtrack(candidates, target))
输出:
[[2, 2, 3], [7]]
阅读全文