-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0040.cpp
More file actions
31 lines (30 loc) · 1.08 KB
/
Copy path0040.cpp
File metadata and controls
31 lines (30 loc) · 1.08 KB
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
class Solution {
private:
int countOccurrences(vector<int> const &v, int start) {
int end = start + 1;
while (end < v.size() && v[end] == v[start]) end++;
return end - start;
}
void pushCombinations(vector<vector<int>> &combinations, vector<int> const &candidates, int start, vector<int> ¤t, int target) {
if (target < 0) return;
if (target == 0) {
combinations.push_back(current);
return;
}
int i = start;
while (i < candidates.size()) {
current.push_back(candidates[i]);
pushCombinations(combinations, candidates, i + 1, current, target - candidates[i]);
current.pop_back();
i += countOccurrences(candidates, i);
}
}
public:
vector<vector<int>> combinationSum2(vector<int> &candidates, int target) {
vector<vector<int>> combinations;
sort(candidates.begin(), candidates.end());
vector<int> current;
pushCombinations(combinations, candidates, 0, current, target);
return combinations;
}
};