2017-05-23 123 views
-3
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

因爲當你做self.ans.append(tmp[:]),你在self.ans追加tmp的副本。因此,無論何時將tmp get添加到self.ans中,都會添加新列表tmp。因此,即使tmp稍後更改,它也不會影響添加到self.ans的實際列表。

現在,當你做self.ans.append(tmp),你只是將相同的列表tmp添加到self.ans而不是它的副本。因此,以後在tmp上完成的所有操作也會反映在self.ans中,因爲您沒有添加tmp的副本,而只是參考。 在dfs你在做第012最後一行tmp.pop(),這將清空tmp列表。這就是爲什麼self.ans已將所有的tmp列出爲空。

+0

感謝您的解釋! – user8051764