class Solution(object):
"""
@param candidates: Given the candidate numbers
@param target: Given the target number
@return: All the combinations that sum to target
"""
def combinationSum2(self, candidates, target):
# write your code here
candidates.sort()
self.ans, tmp, use = [], [], [0] * len(candidates)
self.dfs(candidates, target, 0, 0, tmp, use)
return self.ans
def dfs(self, can, target, p,
now, tmp, use):
if now == target:
print(tmp)
self.ans.append(tmp[:])
return
for i in range(p, len(can)):
if now + can[i] <= target and (i == 0 or can[i] != can[i-1] or use[i-1] == 1):
tmp.append(can[i])
use[i] = 1
self.dfs(can, target, i+1, now + can[i], tmp, use)
tmp.pop()
use[i] = 0
s = Solution()
can = [10, 1, 2, 7, 6, 1, 5]
tar = 8
print(s.combinationSum2(can,tar))
如果我用self.ans.append(tmp)替换self.ans.append(tmp [:]),结果将显示为[[],[],[],[]]但不是结果我想要。
答案 0 :(得分:0)
因为当您执行self.ans.append(tmp[:])
时,您要在tmp
中附加self.ans
的副本。因此,只要tmp get被添加到self.ans
中,就会添加新列表tmp
。因此,即使稍后更改tmp
,也不会影响添加到self.ans
的实际列表。
现在,当您执行self.ans.append(tmp)
时,您只是将相同的列表tmp
添加到self.ans
而不是它的副本中。因此,稍后在tmp
上完成的所有操作也会反映在self.ans
中,因为您没有添加tmp
的副本,而只是一个引用。
在dfs
,您在最后一行进行tmp.pop()
,这会连续清空列表tmp
。这就是self.ans
所有tmp
列表为空的原因。