-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00039-combination_sum.cpp
55 lines (41 loc) · 1.26 KB
/
00039-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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 39: Combination Sum
// https://leetcode.com/problems/combination-sum/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
private:
void backtrack(vector<int>& candidates, int target, int start, vector<int>& current, vector<vector<int>>& result) {
if (start >= candidates.size() || target < 0) return;
if (target == 0) {
result.push_back(current);
return;
}
current.push_back(candidates[start]);
backtrack(candidates, target - candidates[start], start, current, result);
current.pop_back();
backtrack(candidates, target, start+1, current, result);
}
public:
// SOLUTOIN
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> current;
vector<vector<int>> result;
backtrack(candidates, target, 0, current, result);
return result;
}
};
int main() {
Solution o;
// INPUT
vector<int> candidates = {2,3,6,7};
int target = 7;
// OUTPUT
auto result = o.combinationSum(candidates, target);
cout << "["; for (auto x : result) {
cout << "["; for (auto y : x) {
cout << y << ",";
} cout << "\b],";
} cout << "\b]" << endl;
return 0;
}