添加列表以在python中列出问题

时间:2017-05-23 06:41:27

标签: python

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 [:]),结果将显示为[[],[],[],[]]但不是结果我想要。

1 个答案:

答案 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列表为空的原因。