forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination-sum_1_AC.cpp
More file actions
30 lines (28 loc) · 884 Bytes
/
combination-sum_1_AC.cpp
File metadata and controls
30 lines (28 loc) · 884 Bytes
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
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> v;
dfs(0, 0, v, res, candidates, target);
return res;
}
private:
void dfs(int idx, int sum, vector<int> &v, vector<vector<int>> &res, vector<int> &candidates, int target) {
if (idx == candidates.size()) {
if (sum == target) {
res.push_back(v);
}
return;
}
int i, j;
for (i = 0; sum + i * candidates[idx] <= target; ++i) {
for (j = 0; j < i; ++j) {
v.push_back(candidates[idx]);
}
dfs(idx + 1, sum + i * candidates[idx], v, res, candidates, target);
for (j = 0; j < i; ++j) {
v.pop_back();
}
}
}
};