Problems178
Search for a command to run...
Initialization
Walk the candidates from the back. At each one, either drop it for good (index moves down) or take it and stay put so it can be taken again. Reaching sum = 0 collects a combination.
Pick / Drop Recursion
1function func(v, i, sum, v2, ans) {2 // Target met exactly3 if (sum === 0) {4 ans.push([...v2]);5 return;6 }7 8 // Overshot, or no candidates left9 if (sum < 0 || i < 0) {10 return;11 }12 13 // Drop candidate i entirely14 func(v, i - 1, sum, v2, ans);15 16 // Take candidate i — index stays, so it can repeat17 v2.push(v[i]);18 func(v, i, sum - v[i], v2, ans);19 20 // Undo21 v2.pop();22}23 24function combinationSum(candidates, target) {25 const ans = [];26 const v2 = [];27 func(candidates, candidates.length - 1, target, v2, ans);//target: 7ans: []28 return ans;29}