递归 dfs深度优先
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
result = list()
self.dfs(candidates, target, -1, [], result)
return result
def dfs(self, candidates, target, index, path, result):
if target < 0:
return
if target == 0:
result.append(path)
for i in range(index + 1, len(candidates)):
if i > index + 1 and candidates[i] == candidates[i - 1]:
continue
self.dfs(candidates, target - candidates[i], i, path + [candidates[i]], result)