Skip to content

Backtracking: try, undo, try the next

Working knowledgeConcept

Listing every subset or every ordering looks like it needs one loop per item, and you do not know how many items there are. Backtracking does it with one list: add a choice, go deeper, then take the choice back on the way up.

01 Every option, with no fixed number of loops

For [1, 2, 3] there are 8 subsets: each number is either in or out, so 2 × 2 × 2. With three items you could write three nested loops. With n items you would need n loops, and you cannot write a number of loops that depends on the input.

Recursion gives you that: each call makes one choice and calls itself for the rest. The depth of the calls plays the part of the nested loops.

02 The shape: a tree of choices

Each level decides one number: take it or skip it. Each leaf is one finished subset.
Decisions for [1, 2, 3]
start
+1
+2
+3{1,2,3}
no 3{1,2}
no 2
+3{1,3}
no 3{1}
no 1
+2
+3{2,3}
no 3{2}
no 2
+3{3}
no 3{}
  • a finished subset

A path from the root to a leaf is one sequence of choices. Backtracking walks every such path, left to right.

You never build this tree in memory. You walk it, and at any moment you only hold the one path you are on.

03 Choose, explore, undo

All backtracking code has the same three moves around the recursive call. Choose changes the shared path. Explore recurses with that choice in place. Undo reverses the change, so the next choice starts from the same state as this one did.

subsets.py
def subsets(nums):
out, path = [], []
def walk(i):
if i == len(nums):
out.append(path[:]) # record a copy
return
path.append(nums[i]) # choose: take nums[i]
walk(i + 1) # explore
path.pop() # undo
walk(i + 1) # the other choice: skip it
walk(0)
return out
print(subsets([1, 2])) # [[1, 2], [1], [2], []]

The undo is what lets one path list serve every branch. Without it, the 2 taken on the left would still be there when you try the right.

04 Watch the path grow and shrink

subsets([1, 2]): one append or pop per step
Step 1 of 12
path · the choices so far
Empty
out · recorded subsets
Empty
Decision tree for [1, 2]
start
take 1
take 2
skip 2
skip 1
take 2
skip 2
  • just added
  • deciding now
  • on the current path
  • leaf recorded
  • not reached yet

walk(0) starts at the root with an empty path. Nothing is recorded yet.

0 subsets found

path is used like a stack: it grows by one on the way down and shrinks by one on the way back up. It always matches the call stack, one entry per take on the current path.

05 Record a copy, not the list

At a leaf, out.append(path) stores a reference to the one shared list. Every later undo changes it. When the walk ends, path is empty, so every entry in out shows an empty list.

Stores the list
out.append(path)
# subsets([1, 2])
# [[], [], [], []]
Stores a copy
out.append(path[:])
# subsets([1, 2])
# [[1, 2], [1], [2], []]

06 More choices per step, and pruning

For permutations, each level picks any unused number, so the choice is a loop instead of take-or-skip. The pattern is the same. used is extra state, so it gets its own choose and undo.

permute.py
def permute(nums):
out, path = [], []
used = [False] * len(nums)
def walk():
if len(path) == len(nums):
out.append(path[:])
return
for i, x in enumerate(nums):
if used[i]:
continue # prune: already in the path
used[i] = True # choose
path.append(x)
walk() # explore
path.pop() # undo, in reverse order
used[i] = False

The continue is pruning: a branch that cannot lead to a valid answer is skipped before you walk into it. In N-Queens you skip any square a placed queen already attacks, which cuts away most of the tree.

Subsets of n2ⁿ leavesTwo choices per item. For n = 20, about a million.
Permutations of nn! leavesn choices, then n − 1, … For n = 10, 3,628,800.
With pruningFewer branchesStill exponential in the worst case, but dead branches are cut where they start.

07 When it goes wrong

path.append(x) walk() # no path.pop()A missing undoChoices from finished branches leak into the next one. Results come out too long, or the walk stops early because len(path) is already full.
used[i] = True path.append(x) walk() path.pop()Undoing only part of the choiceEvery bit of state the choice changed needs undoing. Here used[i] stays True, so later branches think x is taken.
permute([1, 1, 2])Repeated values give repeated answersThe two 1s are different positions, so the same ordering appears twice. Sort first and skip a value equal to the one before it, unless that one is in use.
if len(path) == n and is_valid(path):Checking only at the leafTesting validity at the end walks the whole tree. Check as soon as a choice is made and stop that branch at once.

08 Check yourself

Question

In subsets, what does path hold right after path.pop() runs?

Question

Your subsets returns [[], [], [], []]. What is the bug?

Question

How many leaves does the permutation walk for [1, 2, 3, 4] reach?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?