-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),結果將顯示爲[],[], [],[]]但不是我想要的結果。添加列表,列出問題蟒蛇
感謝您的解釋! – user8051764