-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathCombination Sum.cpp
29 lines (26 loc) · 967 Bytes
/
Combination Sum.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
29
class Solution {
public:
//global values shared between both functions
vector<vector<int>>result;
vector<int>current;
int sum;
void function(vector<int>& candidates,int target,int index)
{
if(sum>target)return ;//base case if sum is greater then target then return
if(sum==target){
result.push_back(current);//if sum is equal to target then just add current to result
}
for(int i=index;i<candidates.size();i++){
sum+=candidates[i];//and current value to sum
current.push_back(candidates[i]);//and current value to current vector
function(candidates,target,i);//again reccure for same index i
sum-=candidates[i];//back track mean remove value that previously added
current.pop_back();//remove the value that previously added to current
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sum=0;
function(candidates,target,0);
return result;
}
};