Problem description

Combination Sum II

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:

1
2
3
4
5
6
7
8
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]
]

Example 2:

1
2
3
4
5
6
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]

这道题跟 Combination Sum 类似,不同的是,每个 candidate 只能用一次,所以在递归调用中,findComSum(candidates, i + 1, target - candidates[i], one, res);i + 1 开始。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
vector< vector<int> > combinationSum2(vector<int>& candidates, int target) {
vector < vector <int> > res;
vector <int> one;
if(candidates.empty())
return res;
sort(candidates.begin(),candidates.end()); // sort candidates
findComSum(candidates, 0, target, one, res);
return res;
}
void findComSum(vector<int> &candidates, int start, int target, vector<int> &one, vector< vector<int> >&res){
if(target == 0){
res.push_back(one);
return;
}
for(int i = start; i < candidates.size(); i++){
if(i > start && candidates[i] == candidates[i-1])
continue;
if(candidates[i] <= target){
one.push_back(candidates[i]);
findComSum(candidates, i + 1, target - candidates[i], one, res);
one.pop_back();
}
}
}
};