-
Notifications
You must be signed in to change notification settings - Fork 993
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #36 from rachitkewl/patch-3
Mock Coding Interview - Combination Sum Problem
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
}; |