-
Notifications
You must be signed in to change notification settings - Fork 0
/
combinationSum2.cpp
34 lines (28 loc) · 1.07 KB
/
combinationSum2.cpp
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
28
29
30
31
32
33
34
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int> > results;
vector<int> currentSubset;
sort(candidates.begin(), candidates.end());
generateCombinations(0, results, candidates, currentSubset, target);
return results;
}
void generateCombinations(int index, vector<vector<int>>& results,
vector<int> candidates, vector<int> currentSubset,
int target) {
int sum = accumulate(currentSubset.begin(), currentSubset.end(), 0);
if(sum == target) {
results.push_back(currentSubset);
}
else if(sum < target) {
for(int i = index; i < candidates.size(); i++) {
if(i > index && candidates[i-1] == candidates[i]) {
continue;
}
currentSubset.push_back(candidates[i]);
generateCombinations(i+1, results, candidates, currentSubset, target);
currentSubset.pop_back();
}
}
}
};