Skip to content

Commit ee7f9ae

Browse files
authored
Mock Coding Interview - Combination Sum Problem
Refer to https://bit.ly/MockInterviewSeries to watch free on YouTube.
1 parent 05fc654 commit ee7f9ae

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

LeetCode/39.combination-sum.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using choice = vector<int>;
2+
vector<int> arr = {};
3+
4+
// returning all possible choices to make target sum by using suffix of array [curIndex, ...]
5+
vector<choice> getAllChoices(int curIndex, int target) {
6+
// base case
7+
if(target < 0) return {}; // no valid choice
8+
if(target == 0) return {{}}; // one choice, and you chose nothing
9+
if(curIndex == arr.size()) return {};
10+
11+
int curNumber = arr[curIndex];
12+
13+
vector<choice> ans = getAllChoices(curIndex+1, target); // curNumber is not used at all
14+
15+
vector<choice> other = getAllChoices(curIndex, target - curNumber); // using it once
16+
for(choice c: other) {
17+
c.push_back(curNumber);
18+
// now c is a valid choice
19+
ans.push_back(c);
20+
}
21+
22+
return ans;
23+
}
24+
25+
class Solution {
26+
27+
public:
28+
vector<choice> combinationSum(vector<int>& candidates, int target) {
29+
arr = candidates;
30+
return getAllChoices(0, target);
31+
}
32+
};

0 commit comments

Comments
 (0)