我实现了一个组合求和算法来解决以下问题:
# Given an array: [10,1,2,7,6,1,5]
# and a target: 8
# Find the solution set that adds up to the target
# in this case:
# [1, 7]
# [1, 2, 5]
# [2, 6]
# [1, 1, 6]
def cominbationSum(arr, target):
arr =sorted(arr)
res = []
path = []
dfs_com(arr, 0, target, path, res)
return res
def dfs_com(arr, curr, target, path, res):
if target == 0:
res.append(path)
return
if target < 0:
return
for i in range(curr, len(arr)):
if i > curr and arr[i] == arr[i-1]: # skip duplicates
continue
path.append(arr[i])
dfs_com(arr, i+1, target - arr[i], path, res)
path.pop(len(path)-1)
print cominbationSum([10,1,2,7,6,1,5], 8)
我的算法生成正确的组合,但在返回res
时遇到问题。它将res
返回为[[],[],[],[]]
,而不是[[1, 1, 6],[1, 2, 5],[1, 7],[2, 6]]
。知道路径为什么不能正确地附加到res上吗?在
换行
到
^{pr2}$所以你得到的是路径的副本而不是路径本身。问题是因为您要删除行中的元素:
看来是个参考问题。尝试:
这将创建}内的列表产生任何影响。在
path
的一个浅拷贝,因此在代码中稍后对path
执行的任何pop
都不会对{相关问题 更多 >
编程相关推荐