Backtracking
Walk into a maze with a piece of chalk. When you hit a dead end, step back to the last fork and try the next turn, never walking the same dead end twice. Backtracking explores choices the same way, undoing each step so every option gets exactly one visit.
2 · Watch
Backtracking in 60 seconds
3 · Now you drive
Keys:←→ stepSpace playR resetHomeEnd jump
Combination Sum
or try
2–4 different numbers from 2 to 9, then | and a target from 1 to 10.Sort the candidates. Start with an empty path. You need 7.Step 1 of 20. Sorted candidates 2, 3, 6, 7. Path empty. Need 7. Nothing found yet.
Step 1 of 20
solution.ts
function combinationSum(candidates: number[], target: number): number[][] {
const result: number[][] = [];
const path: number[] = [];
candidates.sort((a, b) => a - b);
function dfs(start: number, remaining: number) {
if (remaining === 0) {
result.push([...path]);
return;
}
for (let i = start; i < candidates.length; i++) {
if (candidates[i] > remaining) break;
path.push(candidates[i]);
dfs(i, remaining - candidates[i]);
path.pop();
}
}
dfs(0, target);
return result;
}
▶ marks the line running now
4 · Your turn
0 of 2 problems solved
Start from this
function dfs(path: number[], start: number) {
if (isDone(path)) {
// Save a copy: path keeps changing after this.
results.push([...path]);
return;
}
for (let i = start; i < choices.length; i++) {
// Choose.
path.push(choices[i]);
// Explore from here. i + 1 uses each choice once; pass i to allow repeats.
dfs(path, i + 1);
// Undo, so the next choice starts clean.
path.pop();
}
}Easy ways to go wrong
- Saving path itself instead of a copy.
- Forgetting the undo step after the recursive call.
- Not pruning, so dead branches run all the way down.
- Medium01
Combination Sum
The one you just watched. Write it from memory.
Choose, go deeper, undo, try the next one.
- Time
- O(2^t)
- Space
- O(t)
Also works with 1-D DP.
- Medium02
Word Search
Same try-and-undo walk, stepping to neighbour cells.
Step to a neighbour, mark it, and unmark it on the way back.
- Time
- O(m·n·3^L)
- Space
- O(L)