-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path039_CombinationSum.cpp
59 lines (58 loc) · 1.83 KB
/
039_CombinationSum.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//33.57%
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
if(candidates.empty()) return res;
int size(candidates.size());
return combinationSumHelper(candidates, 0, size, target);
}
private:
vector<vector<int>> combinationSumHelper(vector<int>& candidates, int left, int right, int target){
vector<vector<int>> res;
for(int i = left ; i < right; i++){
int first = candidates[i];
int times(1);
while(first < target){
vector<vector<int>> subRes = combinationSumHelper(candidates, i + 1, right, target - first);
if(!subRes.empty()){
for(auto vec : subRes){
for(int j = 0; j < times; j++)
vec.push_back(candidates[i]);
res.push_back(vec);
}
}
first += candidates[i];
times++;
}
if(first == target){
vector<int> vec(times, candidates[i]);
res.push_back(vec);
}
}
return res;
}
};
//Use backtracing method
class Solution {
public:
std::vector<std::vector<int> > combinationSum(std::vector<int> &candidates, int target) {
std::sort(candidates.begin(), candidates.end());
std::vector<std::vector<int> > res;
std::vector<int> combination;
combinationSum(candidates, target, res, combination, 0);
return res;
}
private:
void combinationSum(std::vector<int> &candidates, int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin) {
if (!target) {
res.push_back(combination);
return;
}
for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i) {
combination.push_back(candidates[i]);
combinationSum(candidates, target - candidates[i], res, combination, i);
combination.pop_back();
}
}
};