1
我實現了一個組合和算法以下問題:組合總和蟒蛇遞歸範圍
# 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?
什麼是python版本? – Kasramvd
@Kasramvd python 2.7 – ApathyBear