-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path40_Combination_Sum_II
26 lines (26 loc) · 980 Bytes
/
40_Combination_Sum_II
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
class Solution {
private:
void helper(vector<vector<int>>& result, vector<int>& current, vector<int>& candidates, int target, int start){
// try to add a number
for (int i = start; i < candidates.size(); ++i){
if (i == start || candidates[i] != candidates[i - 1]){
current.push_back(candidates[i]);
if (candidates[i] == target){
result.push_back(current);
}else if(candidates[i] < target){
helper(result, current, candidates, target - candidates[i], i + 1);
}
current.pop_back();
}
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> result;
if (candidates.empty()) return result;
vector<int> current;
sort(candidates.begin(), candidates.end());
helper(result, current, candidates, target, 0);
return result;
}
};