Skip to content

Commit 118a335

Browse files
author
ZQKC
committed
39.Combination Sum
1 parent 4d94eb6 commit 118a335

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

39.Combination Sum.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
private:
3+
void dfs(const vector<int> &candidates, int pos, int sum, int target, std::vector<int> &path, std::vector<std::vector<int>> &ans) {
4+
if (sum == target) {
5+
ans.push_back(path);
6+
return ;
7+
}
8+
else if (sum > target) {
9+
return ;
10+
}
11+
12+
for (int i = pos; i < candidates.size(); ++i) {
13+
path.push_back(candidates[i]);
14+
dfs(candidates, i, sum + candidates[i], target, path, ans);
15+
path.pop_back();
16+
}
17+
}
18+
public:
19+
vector<vector<int>> combinationSum(vector<int> candidates, int target) {
20+
std::vector<std::vector<int>> ans;
21+
std::vector<int> tmp;
22+
23+
std::sort(candidates.begin(), candidates.end());
24+
dfs(candidates, 0, 0, target, tmp, ans);
25+
26+
return ans;
27+
}
28+
};

0 commit comments

Comments
 (0)