-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathCombinationSumSolution.h
42 lines (36 loc) · 1.13 KB
/
CombinationSumSolution.h
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
38
39
40
41
42
#include <vector>
using namespace std;
class CombinationSumSolution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector<vector<int>> solutions;
vector<int> oneSolution;
dfsSolve(candidates, solutions, oneSolution, 0, target);
return solutions;
}
private:
void dfsSolve(vector<int>& candidates, vector<vector<int>> &solutions, vector<int>& oneSolution, int curSum, int target) {
int last ;
if (oneSolution.size() > 0)
last = oneSolution.back();
else
last = 0;
int rest = target - curSum;
if (rest < 0)
return;
else if (rest == 0) {
solutions.push_back(oneSolution);
return;
}
for (int i = 0; i < candidates.size(); ++i)
{
int cur = candidates[i];
if (cur >= last) {
oneSolution.push_back(cur);
int sum = curSum + cur;
dfsSolve(candidates, solutions, oneSolution, sum, target);
oneSolution.pop_back();
}
}
}
};