DDSA
  • Missions
  • Atlas
  • Lens
  • Lab
←
Atlas · Recursion & graphs · Topic 10 of 18

Backtracking

Build answers one choice at a time; after exploring a choice, undo it and try the next.

Spot it

Signals in the question

⌕"Find all" subsets, permutations, combinations or paths.

⌕Small inputs (n ≤ ~15–20): the answer count itself is exponential.

⌕Placing things under rules: N-Queens, Sudoku, word search.

The idea

O(n · 2ⁿ) for subsets time · O(n) for the path space

At each step, make a choice, recurse, then undo the choice (backtrack). For subsets, each number is either in or out: take it and recurse, then remove it and recurse again.

Template · Choose, explore, undo

1def subsets(nums):2    result, path = [], []3    def dfs(i):4        if i == len(nums):5            result.append(path[:])   # a copy6            return7        path.append(nums[i])         # choose8        dfs(i + 1)                   # explore9        path.pop()                   # undo10        dfs(i + 1)                   # skip it11    dfs(0)12    return result

The template, filled in for Subsets. The highlighted lines are the part every problem of this kind shares.

The best, free

One of each
▶︎WatchBacktracking, explainedNeetCode · YouTube · free↗¶ReadBacktracking algorithmsGeeksforGeeks · free↗

Practice set

Loading your mission…

Common mistakes

1Adding path itself to the results instead of a copy: later changes overwrite it.

2Forgetting to undo the choice, so it leaks into the next branch.

3Duplicates: with repeated numbers, sort and skip equal neighbours at the same level.

Check yourself

Question 1 of 2

How many subsets does a list of n distinct numbers have?