1、相比于正常的回溯算法,多了一个index参数,主要是用来后面的数层去重,树枝不去重
2、递归中的i+1的作用是用过这个元素之后,下次就不用了
3、path[:]的作用和path.copy()的作用相同
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def trace(path, index):
if sum(path) > target:
return
if sum(path) == target:
res.append(path[:])
else:
for i in range(index, n):
if candidates[i] == candidates[i - 1] and i > index:
continue
else:
path.append(candidates[i])
trace(path, i + 1)
path.pop()
candidates.sort()
res = []
n = len(candidates)
trace([], 0)
return res