组合Sum python递归范围

时间:2016-03-15 19:33:50

标签: python algorithm recursion scope

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

create table t(koy int, tablet varchar(10), [time] time,dayz varchar(20),dateOnly date);
insert into t values 
(157,'A','13:27:36 PM','Sat','03/12/2016'),
(157,'A','13:28:06 PM','Sat','03/12/2016'),
(157,'A','13:28:36 PM','Sat','03/12/2016'),
(158,'P','15:25:11 PM','Sat','03/12/2016'),
(158,'P','15:25:41 PM','Sat','03/12/2016'),
(158,'P','15:26:11 PM','Sat','03/12/2016'),
(159,'P','23:26:11 PM','Sat','03/12/2016')

我的算法生成了正确的组合,但返回# 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而不是[[],[],[],[]]。知道为什么路径没有正确附加到res?

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:1)

更改行

old

res.append(path)

所以你得到路径的副本而不是路径本身。问题是因为您要删除此行中的元素:

res.append(path[:])