注意点&感悟:
自己独立写的代码:
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
used = [0] * len(candidates)
self.backtracking(candidates,target,0,[],0,res,used)
return res
def backtracking(self,candidates,target,start_index,path,total,res,used):
# 特殊 终止条件
if total == target:
res.append(path[:])
return
# 核心
for i in range(start_index,len(candidates)):
# 1.去重
if i>0 and candidates[i] == candidates[i-1] and used[i-1] ==0: # used未使用
continue
total += candidates[i]
# 2.过滤
if total > target:
break
path.append(candidates[i])
used[i] = 1
self.backtracking(candidates,target,i+1,path,total,res,used)
used[i] = 0
path.pop()
total -= candidates[i]
通过截图: