-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinations Sum2.cpp
More file actions
37 lines (31 loc) · 1.08 KB
/
Combinations Sum2.cpp
File metadata and controls
37 lines (31 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
32
33
34
35
36
37
class Solution {
private:
int target, n;
vector<int> candidates;
public:
void combinationSum(vector<vector<int> > &result, vector<int> path, int k, int sum) {
if (sum > target) return;
if (sum == target) {
result.push_back(path);
return;
}
for (int i = k; i < n; i++) {
path.push_back(candidates[i]);
combinationSum(result, path, i+1, sum+candidates[i]);
while (i < n-1 && path.back() == candidates[i+1])i++;
path.pop_back();
}
}
vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > result;
sort(candidates.begin(), candidates.end());
this->target = target;
this->candidates = candidates;
this->n = candidates.size();
vector<int> path;
combinationSum(result, path, 0, 0);
return result;
}
};