Backtracking: try, undo, try the next
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
- 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.
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
- 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.
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.
out.append(path)# subsets([1, 2])# [[], [], [], []]
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.
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.
n = 20, about a million.n choices, then n − 1, … For n = 10, 3,628,800.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.