-
Notifications
You must be signed in to change notification settings - Fork 0
/
CombinationSum(Leetcode).cpp
25 lines (23 loc) · 1.09 KB
/
CombinationSum(Leetcode).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
class Solution {
void combination(const vector<int>& candidates, int target, vector<int> &currComb, int currSum, int currIndex, vector<vector<int>>& ans){
if(currSum>target) return; //backtrack
if(currSum==target){
ans.push_back(currComb); //store the solution and backtrack
return;
}
for(int i=currIndex; i<candidates.size(); i++){ //try all possible options for the next level
currComb.push_back(candidates[i]); //put 1 option into the combination
currSum+=candidates[i];
combination(candidates, target, currComb, currSum, i, ans); //try with this combination, whether it gives a solution or not.
currComb.pop_back(); //when this option backtrack to here, remove this and go on to the next option.
currSum-=candidates[i];
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> currComb;
combination(candidates, target, currComb, 0, 0, ans);
return ans;
}
};