Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums toT.
Each number in C 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.
For example, given candidate set[10, 1, 2, 7, 6, 1, 5]and target8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
分析
注意这里 target == 0 加入res . 《0或者重复时候,不一样处理
class Solution:
def combinationSum2(self, c: List[int], target: int) -> List[List[int]]:
c.sort()
res = []
n=len(c)
def dfs(pos,path,target):
if target == 0:
res.append(path)
for i in range(pos,n ):
if c[i] > target:
return
if i!=pos and c[i]==c[i-1]:
continue #!!!!!!
dfs(i+1,path+[c[i]],target - c[i])
dfs(0,[],target)
return res