1. Target hit
A path that brings remaining to zero is a valid combination.
if (remaining === 0)Typorithm · medium
Step 1 of 8 · intro card
Backtracking
Reach a target sum by choosing candidates with reuse, recursing from i so numbers can repeat.
Each candidate may be used unlimited times, so the same number can appear repeatedly in one combination.
Recursing from i instead of i + 1 is what permits reuse while still avoiding permuted duplicates.
Subtract the chosen value from remaining; hitting zero records a valid combination.
Recurse from i to allow reuse.
Base case: remaining is 0.
Skip candidates larger than remaining.
function combinationSum(candidates, target) {
const result = [];
function backtrack(start, path, remaining) {
if (remaining === 0) {
result.push([...path]);
return;
}
for (let i = start; i < candidates.length; i += 1) {
if (candidates[i] > remaining) continue;
path.push(candidates[i]);
backtrack(i, path, remaining - candidates[i]);
path.pop();
}
}
backtrack(0, [], target);
return result;
}Connect each part of the code to the concept before you type.
A path that brings remaining to zero is a valid combination.
if (remaining === 0)Skip candidates larger than what is left to reach.
if (candidates[i] > remaining) continueAdd the candidate to the current path.
path.push(candidates[i])Recursing from i (not i + 1) lets the same number be reused.
backtrack(i, path, remaining - candidates[i])Remove the candidate to try the next one.
path.pop()Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputCandidates 2,3,5 · target 5
Follow temporary values, local state and supporting structures at this step.
Live recursive calls, including their arguments. Returning releases the top frame.
Current choice path0 entries
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state