File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ var combinationSum = function ( candidates , target ) {
2+ let results = [ ] ;
3+
4+ function helper ( idx , curr , total ) {
5+ // base case - when total = target push into results
6+ if ( total === target ) {
7+ results . push ( [ ...curr ] ) ;
8+ return ;
9+ }
10+ // base exit case - when the index is greater or equal to candidates or the total is greater than target, exit
11+ if ( idx >= candidates . length || total > target ) {
12+ return ;
13+ }
14+
15+ // recursive case
16+ // case where we include the current value without advancing the index
17+ curr . push ( candidates [ idx ] ) ;
18+ helper ( idx , curr , total + candidates [ idx ] ) ;
19+ curr . pop ( )
20+ // case where we advance the index
21+ helper ( idx + 1 , curr , total ) ;
22+ }
23+ helper ( 0 , [ ] , 0 ) ;
24+
25+ return results ;
26+ } ;
27+
28+ // time - O(2^n) backtracking
29+ // space - O(1)
You can’t perform that action at this time.
0 commit comments