File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments