Skip to content

Commit

Permalink
Create 39. Combination Sum.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
Manikant69 authored Apr 26, 2024
1 parent d4b5142 commit 6228b7b
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions 39. Combination Sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution {
private:
void solve(vector<int>& candidates, int target, int index, vector<int>&temp, vector<vector<int>> &ans)
{
if(target == 0){
ans.push_back(temp);
return;
}
if(target < 0 || index >= candidates.size()){
return;
}

//include
temp.push_back(candidates[index]);
solve(candidates, target-candidates[index], index, temp, ans);
//backtrack
temp.pop_back();


//exclude
solve(candidates, target, index+1, temp, ans);

}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
vector<vector<int>> ans;
vector<int>temp;
solve(candidates, target, 0, temp, ans);

return ans;
}
};

0 comments on commit 6228b7b

Please sign in to comment.