forked from garvit-bhardwaj/Leetcode-Problems-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombinationSum.cpp
28 lines (25 loc) · 839 Bytes
/
CombinationSum.cpp
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 {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> sum;
combinationSumHelper(candidates, target, 0, sum, ans);
return ans;
}
void combinationSumHelper(vector<int>& candidates, int target, int idx, vector<int>& sum, vector<vector<int>>& ans)
{
if(target==0 && idx<candidates.size())
{
ans.push_back(sum);
return;
}
if(target<0 || idx>=candidates.size())
{
return;
}
sum.push_back(candidates[idx]);
combinationSumHelper(candidates,target-candidates[idx],idx,sum,ans);
sum.pop_back();
combinationSumHelper(candidates,target,idx+1,sum,ans);
}
};