forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination-sum.cpp
More file actions
30 lines (26 loc) · 820 Bytes
/
combination-sum.cpp
File metadata and controls
30 lines (26 loc) · 820 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
// Solved using backtracking
class Solution {
public:
void recur(vector<vector<int>>& ans, vector<int>& v, vector<int>& candidates, int target, int curr){
if(target==0){
ans.push_back(v);
}
if(target<0){
return;
}
for(int i = curr; i< candidates.size(); i++){
if(candidates[i]<=target){
v.push_back(candidates[i]);
recur(ans,v,candidates,target-candidates[i],i);
v.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>>ans;
vector<int> v;
sort(candidates.begin(), candidates.end());
recur(ans,v,candidates,target,0);
return ans;
}
};