forked from rachitiitr/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39.combination-sum.cpp
More file actions
32 lines (25 loc) · 941 Bytes
/
39.combination-sum.cpp
File metadata and controls
32 lines (25 loc) · 941 Bytes
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
26
27
28
29
30
31
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);
}
};