Skip to content

Start typing to search patterns, problems and pages.

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.

⏱ about 20 minutesNeeds: recursion, arraysTime ExponentialSpace O(depth)

2 · Watch

Backtracking in 60 seconds

Which sets of 2, 3, 6 and 7 add to 7? Trying every branch blindly means 28 nodes, most of them dead ends that overshoot.

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.
  1. Medium01

    Combination Sum

    LeetCode 39 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

  2. Medium02

    Word Search

    LeetCode 79 · Blind 75 · NeetCode 150

    Same try-and-undo walk, stepping to neighbour cells.

UP NEXT · LESSON 13 OF 20GraphsExplore neighbours with BFS and DFS.