@@ -17,15 +17,22 @@ function combinationSum(
1717
1818 let candidate = candidates [ index ] ;
1919 let newSum = currentSum + candidate ;
20+ let newCurrent = current . concat ( candidate ) ;
2021
2122 if ( newSum <= target ) {
22- combinationSum ( candidates , target , solution , current . concat ( candidate ) , newSum , index ) ;
23+ combinationSum ( candidates , target , solution , newCurrent , newSum , index ) ;
2324 } else if ( index < candidates . length - 1 ) {
2425 const newIndex = index + 1 ;
25- while ( currentSum + candidates [ newIndex ] > target ) current . pop ( ) ;
2626 candidate = candidates [ newIndex ] ;
27- newSum = currentSum + candidate ;
28- combinationSum ( candidates , target , solution , current . concat ( candidate ) , newSum , newIndex ) ;
27+ newSum = currentSum ;
28+ const reducedCurrent = current . slice ( ) ; // clone current
29+ while ( newSum + candidate > target ) {
30+ const deletedCandidate = reducedCurrent . pop ( ) ;
31+ newSum -= deletedCandidate ;
32+ }
33+ newSum += candidate ;
34+ newCurrent = reducedCurrent . concat ( candidate ) ;
35+ combinationSum ( candidates , target , solution , newCurrent , newSum , newIndex ) ;
2936 }
3037
3138
0 commit comments