-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
50 lines (42 loc) · 1.03 KB
/
Solution.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
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
private:
void dfs(vector<int> const& candidates,
vector<vector<int>>& combinations,
vector<int>& current,
int target,
int idx) {
if (target == 0) {
combinations.push_back(current);
return;
}
if (idx >= candidates.size()) {
return;
}
if (target < 0) {
return;
}
current.push_back(candidates[idx]);
dfs(candidates, combinations, current, target - candidates[idx], idx);
current.pop_back();
dfs(candidates, combinations, current, target, idx + 1);
return;
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> combinations;
vector<int> current;
dfs(candidates, combinations, current, target, 0);
return combinations;
}
};