Backtracking

Backtracking builds an answer one choice at a time and undoes each choice to try the next, so it walks every branch of a tree of choices.

Subsets: every call records one

StopSearch tree
nums
the first call, running[]
path[]
recordedanswer 1
  • this call
  • on the path
  • answer, in order
  • pruned
  • returned
  • not reached
nums
  1. 1
  2. 2
  3. 3
path
empty
result
  1. []
start0

1/23backtrack(0) starts with an empty path. Record [], the empty subset.

  • CH1 path
Typical cost Exponential in the worst case; pruning is what makes it tractableFull lesson: Subsets →

When to reach for it

  • You're asked for all of something: subsets, orderings, combinations, placements.
  • An answer is a sequence of choices, each from a small set.
  • Some partial answers can already be ruled out, so whole branches can be cut.
  • The output itself is exponential, so nothing much faster exists.

What stays true

Each choice is appended just before its call and popped just after the call returns. So when a call runs, the path holds its own choices and nothing left over from a sibling.

The path is the way down

StopSearch tree
InvariantThe path holds exactly the choices from the first call down to the running one.✓ Holds
the first call, running[]
path[]
  • this call
  • on the path
  • answer, in order
  • pruned
  • returned
  • not reached
nums
  1. 1
  2. 2
  3. 3
path
empty
result[]

1/53Start with an empty path: every number is free.

  • CH1 path

Break it

Each input here has tripped up a version of this code. The stage runs the one that gets it right.

Recursing with i + 1 instead of i would allow 2 only once and miss [2, 2, 2, 2].

Backtracking on the inputs that trip it up

StopSearch tree
the first call, running8
path[]
  • this call
  • on the path
  • answer, in order
  • pruned
  • returned
  • not reached
candidates
  1. 2
path
empty
result[]
remaining8

1/15Sort the candidates: [2]. Start with remaining = 8 and an empty path.

  • CH1 path
Answer[[2, 2, 2, 2]]Steps15

Variants

Permutations

53/53
StopSearch tree
the first call, returned[]call after choosing 1, returned1call after choosing 2, returned2call after choosing 3, answer 13✓call after choosing 3, returned3call after choosing 2, answer 22✓call after choosing 2, returned2call after choosing 1, returned1call after choosing 3, answer 33✓call after choosing 3, returned3call after choosing 1, answer 41✓call after choosing 3, returned3call after choosing 1, returned1call after choosing 2, answer 52✓call after choosing 2, returned2call after choosing 1, answer 61✓
  • this call
  • on the path
  • answer, in order
  • pruned
  • returned
nums
  1. 1
  2. 2
  3. 3
path
empty
result
  1. [1, 2, 3]
  2. [1, 3, 2]
  3. [2, 1, 3]
  4. [2, 3, 1]
  5. [3, 1, 2]
  6. [3, 2, 1]
  • CH1 path

Try every unused number at each place, and free it again on the way back.

Step through it →

Combination sum

38/38
StopSearch tree
2222363363336667the first call, returned7call after choosing 2, returned5call after choosing 2, returned3call after choosing 2, returned1call after choosing 2, pruned✗call after choosing 3, answer 10✓call after choosing 6, pruned✗call after choosing 3, returned2call after choosing 3, pruned✗call after choosing 6, pruned✗call after choosing 3, returned4call after choosing 3, returned1call after choosing 3, pruned✗call after choosing 6, pruned✗call after choosing 6, returned1call after choosing 6, pruned✗call after choosing 7, answer 20✓
  • this call
  • on the path
  • answer, in order
  • pruned
  • returned
candidates
  1. 2
  2. 3
  3. 6
  4. 7
path
empty
result
  1. [2, 2, 3]
  2. [7]
  • CH1 path

Recurse from the same index to reuse a candidate, and stop once one is too big.

Step through it →

The code

The same algorithm in plain Python. The lit line is the one the current frame came from.

Subsets: every call records one

StopSearch tree
the first call, running[]
path[]
recordedanswer 1
  • this call
  • on the path
  • answer, in order
  • pruned
  • returned
  • not reached
nums
  1. 1
  2. 2
  3. 3
path
empty
result
  1. []
start0

1/23backtrack(0) starts with an empty path. Record [], the empty subset.

  • CH1 path
subsets.py
def subsets(nums):    result = []    path = []    def backtrack(start):        result.append(path[:])        for i in range(start, len(nums)):            path.append(nums[i])            backtrack(i + 1)            path.pop()    backtrack(0)    return result

Drill it