-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39.Combination Sum.cpp
More file actions
28 lines (25 loc) · 854 Bytes
/
39.Combination Sum.cpp
File metadata and controls
28 lines (25 loc) · 854 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
class Solution {
private:
void dfs(const vector<int> &candidates, int pos, int sum, int target, std::vector<int> &path, std::vector<std::vector<int>> &ans) {
if (sum == target) {
ans.push_back(path);
return ;
}
else if (sum > target) {
return ;
}
for (int i = pos; i < candidates.size(); ++i) {
path.push_back(candidates[i]);
dfs(candidates, i, sum + candidates[i], target, path, ans);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum(vector<int> candidates, int target) {
std::vector<std::vector<int>> ans;
std::vector<int> tmp;
std::sort(candidates.begin(), candidates.end());
dfs(candidates, 0, 0, target, tmp, ans);
return ans;
}
};