-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombination_Sum.cpp
More file actions
29 lines (29 loc) · 870 Bytes
/
Combination_Sum.cpp
File metadata and controls
29 lines (29 loc) · 870 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
/*Combination Sum dfs */
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
vector<int> path;
vector<vector<int>> result;
combinationSum_dfs(result, path, 0, 0, candidates, target);
return result;
}
void combinationSum_dfs(vector<vector<int>> &result,vector<int> path,int start,int sum,vector<int> candidates,int target)
{
if (target == 0)
return;
if (sum == target)
{
sort(path.begin(), path.end());
result.push_back(path);
return;
}
if (sum > target)
return;
for (size_t i = start; i < candidates.size(); i++)
{
sum += candidates[i];
path.push_back(candidates[i]);
combinationSum_dfs(result, path, i, sum, candidates, target);
sum -= candidates[i];
path.pop_back();
}
}