Combination Sum II
题目
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
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]
]
思路分析
这道题跟combination sum那道题很类似,但是有两个重要的不同:
- Combination Sum I求和的时候可以重复利用数组中的数字,而Combination Sum II要求每一个数字只能用一次
Combination Sum I给的数组中没有重复的数字,而Combination Sum II给的数组中有重复的数字,所以在实现Combination Sum II的时候要考虑结果去重的问题:
**if i>startIndex and candidates\[i\]==candidates\[i-1\]: continue**
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
def dfs(candidates, target, startIndex, path, result):
if target < 0: return
if target == 0:
result.append(path)
return
for i in range(startIndex, len(candidates)):
if candidates[i] > target: return
if i>startIndex and candidates[i]==candidates[i-1]: continue
dfs(candidates, target-candidates[i], i+1, path+[candidates[i]], result)
result = []
dfs(sorted(candidates), target, 0, [], result)
return result