Skip to content

Commit

Permalink
Merge pull request #36 from rachitkewl/patch-3
Browse files Browse the repository at this point in the history
Mock Coding Interview - Combination Sum Problem
  • Loading branch information
rachitiitr authored Oct 3, 2020
2 parents 05fc654 + ee7f9ae commit a4ac7bb
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions LeetCode/39.combination-sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using choice = vector<int>;
vector<int> arr = {};

// returning all possible choices to make target sum by using suffix of array [curIndex, ...]
vector<choice> getAllChoices(int curIndex, int target) {
// base case
if(target < 0) return {}; // no valid choice
if(target == 0) return {{}}; // one choice, and you chose nothing
if(curIndex == arr.size()) return {};

int curNumber = arr[curIndex];

vector<choice> ans = getAllChoices(curIndex+1, target); // curNumber is not used at all

vector<choice> other = getAllChoices(curIndex, target - curNumber); // using it once
for(choice c: other) {
c.push_back(curNumber);
// now c is a valid choice
ans.push_back(c);
}

return ans;
}

class Solution {

public:
vector<choice> combinationSum(vector<int>& candidates, int target) {
arr = candidates;
return getAllChoices(0, target);
}
};

0 comments on commit a4ac7bb

Please sign in to comment.