-
Notifications
You must be signed in to change notification settings - Fork 0
/
Combination Sum.cpp
37 lines (35 loc) · 1.13 KB
/
Combination Sum.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
35
36
37
#include <iostream>
#include <vector>
class Solution {
public:
void helper(std::vector<int> &candidates,
std::vector<std::vector<int>> &res, std::vector<int> &buffer,
int target, int start) {
if (target == 0) {
std::vector<int> buffer_copy = buffer;
res.push_back(buffer_copy);
return;
}
if (start == candidates.size()) {
return;
}
int val = 0;
while (val <= target) {
helper(candidates, res, buffer, target - val, start + 1);
val += candidates[start];
buffer.push_back(candidates[start]);
}
while (val > 0) {
buffer.pop_back();
val -= candidates[start];
}
}
std::vector<std::vector<int>> combinationSum(std::vector<int> &candidates,
int target) {
std::sort(candidates.begin(), candidates.end(), std::greater<int>());
std::vector<std::vector<int>> res;
std::vector<int> buffer;
helper(candidates, res, buffer, target, 0);
return res;
}
};