forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
58 lines (45 loc) · 1.33 KB
/
main.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
/// Source : https://leetcode.com/problems/combination-sum/description/
/// Author : liuyubobobo
/// Time : 2018-03-04
#include <iostream>
#include <vector>
using namespace std;
/// Backtrack
/// Time Complexity: O(n^n)
/// Space Complexity: O(target)
class Solution {
public:
vector<vector<int>> combinationSum(vector<int> &candidates, int target) {
vector<vector<int>> res;
vector<int> cur_res;
solve(candidates, 0, target, cur_res, res);
return res;
}
private:
void solve(const vector<int> &candidates, int index, int target,
vector<int>& cur_res, vector<vector<int>>& res){
if(target == 0){
res.push_back(cur_res);
return;
}
for(int i = index ; i < candidates.size() ; i ++)
if(target >= candidates[i]){
cur_res.push_back(candidates[i]);
solve(candidates, i, target - candidates[i], cur_res, res);
cur_res.pop_back();
}
return;
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
vector<int> candidates = {2, 3, 6, 7};
vector<vector<int>> res = Solution().combinationSum(candidates, 7);
for(const vector<int>& a_res: res)
print_vec(a_res);
return 0;
}