组合和python递归作用域

组合和python递归作用域,python,algorithm,recursion,scope,Python,Algorithm,Recursion,Scope,我对以下问题实施了组合求和算法: # 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 = []

我对以下问题实施了组合求和算法:

# 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)
#给定一个数组:[10,1,2,7,6,1,5]
#目标:8
#找到添加到目标的解决方案集
#在这种情况下:
# [1, 7]
# [1, 2, 5]
# [2, 6]
# [1, 1, 6]
def CominBasionSum(arr,目标):
arr=已排序(arr)
res=[]
路径=[]
dfs_com(arr、0、目标、路径、res)
返回res
def dfs_com(arr、curr、target、path、res):
如果目标==0:
res.append(路径)
回来
如果目标<0:
回来
对于范围内的i(电流、长度(arr)):
如果i>curr和arr[i]==arr[i-1]:#跳过重复项
持续
append(arr[i])
dfs_com(arr,i+1,目标-arr[i],路径,分辨率)
path.pop(len(path)-1)
打印CominBasionSum([10,1,2,7,6,1,5],8)

我的算法生成正确的组合,但返回
res
时有问题。它将
res
返回为
[[]、[]、[]、[]、[]]
而不是
[[1,1,6]、[1,2,5]、[1,7]、[2,6]]
。知道为什么path没有正确地附加到res吗?

看起来像是一个参考问题。尝试:

if target == 0:
    res.append(path[:])
    return

这将创建
path
的浅层副本,因此在代码中稍后对
path
执行的任何
pop
都不会对
res
中的列表产生影响。尝试:

if target == 0:
    res.append(path[:])
    return
这将创建
path
的浅层副本,因此在代码中稍后对
path
执行的任何
pop
都不会对
res
中的列表产生影响,请更改行

res.append(path)

因此,您得到的是路径的副本,而不是路径本身。问题是因为您正在删除此行中的元素:

path.pop(len(path)-1)
换线

res.append(path)

因此,您得到的是路径的副本,而不是路径本身。问题是因为您正在删除此行中的元素:

path.pop(len(path)-1)

python版本是什么?@Kasramvd python 2.7 python版本是什么?@Kasramvd python 2.7