-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinations.cpp
More file actions
30 lines (26 loc) · 839 Bytes
/
Combinations.cpp
File metadata and controls
30 lines (26 loc) · 839 Bytes
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
#include <vector>
#include <algorithm>
class Solution {
private:
std::vector<std::vector<int>> answer;
public:
std::vector<std::vector<int>> combinationSum(std::vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
helper(candidates, 0, target, 0, {});
return answer;
}
void helper(std::vector<int>& candidates, int sum, int target, int index, std::vector<int> currComb) {
if (sum > target) {
return;
} else if (sum == target) {
answer.push_back(currComb);
return;
}
for (int i=index; i<candidates.size(); i++) {
currComb.push_back(candidates[i]);
helper(candidates,sum+candidates[i], target, i, currComb);
currComb.pop_back();
}
return;
}
};