Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
这道题和Combination Sum的思路是一致的,只是这里的数字不能重复使用。(如果candidates里出现重复数字可以使用)
为了提高效率,我们用sort对candidates进行排序,遇到比target大的数字直接break。
然后设定一个起始的索引值,每次遍历便不会出现重复使用情况
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
self.res=[]
candidates.sort()
self.candidates=candidates
self.dfs(0, [], target)
return self.res
def dfs(self,start,path,target):
if target==0:
self.res.append(path)
return
for i in range(start,len(self.candidates)):
if self.candidates[i]>target:break
if i>start and self.candidates[i]==self.candidates[i-1]:continue
self.dfs(i+1, path+[self.candidates[i]], target-self.candidates[i])