File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 1+ var combinationSum = function ( candidates , target ) {
2+ let output = [ ] ;
3+
4+ // Helper function for depth-first search
5+ const dfs = ( index , currentVal , arr ) => {
6+ // If the remaining value is less than 0, no need to proceed further
7+ if ( currentVal < 0 ) return ;
8+ // If we have found a valid combination
9+ if ( currentVal === 0 ) {
10+ output . push ( [ ...arr ] ) ;
11+ return ;
12+ }
13+
14+ // Iterate over the candidates starting from the current index
15+ for ( let i = index ; i < candidates . length ; i ++ ) {
16+ arr . push ( candidates [ i ] ) ;
17+ dfs ( i , currentVal - candidates [ i ] , arr ) ;
18+ arr . pop ( ) ; // backtrack
19+ }
20+ } ;
21+
22+ // Start DFS with the initial target and empty combination
23+ dfs ( 0 , target , [ ] ) ;
24+
25+ return output ;
26+ } ;
You can’t perform that action at this time.
0 commit comments