Sub topic 2
Thinking in State-Space Trees
This chapter assumes you can write recursive Python functions with base cases, work with lists, and read Big-O notation. It builds on the previous chapter's picture of the call stack: each recursive call gets its own frame, and the frame disappears when the call returns.
Backtracking is a way to search through every way of making a sequence of decisions. That description gets much easier to work with once you draw the search as a tree. The tree is the model you design before you write any code, and most bugs in backtracking come from a tree that was never designed clearly.
What a State Is
A state is a snapshot of a search in progress. It has two parts:
- The partial solution: the decisions made so far, such as "1 and 3 are chosen."
- The remaining decisions: what is still left to decide, such as "consider elements from index 2 onward."
A state-space tree is the set of all reachable states, arranged by how you get from one to another:
- The root is the empty state, where nothing has been decided.
- Each edge is one choice that extends a partial solution.
- Each node is a partial solution.
- A leaf is a state with no further choices. It is either a complete solution or a dead end.
The algorithm never builds this tree in memory. The tree describes the order in which a recursive function visits states. Each recursive call corresponds to one node, and each loop iteration inside that call corresponds to one outgoing edge.
One Problem, Two Trees
You can usually model a problem with more than one tree. Take the problem of listing every subset of [1, 2, 3].
Model A: Include or Exclude
At depth i, decide whether element i is in the subset. Every node has exactly two children, and every subset appears as a leaf at depth n.
def show_include_exclude(nums):
def visit(i, path, depth):
print(" " * depth + str(path))
if i == len(nums):
return
visit(i + 1, path + [nums[i]], depth + 1) # include nums[i]
visit(i + 1, path, depth + 1) # exclude nums[i]
visit(0, [], 0)
show_include_exclude([1, 2, 3])Output:
[]
[1]
[1, 2]
[1, 2, 3]
[1, 2]
[1]
[1, 3]
[1]
[]
[2]
[2, 3]
[2]
[]
[3]
[]The tree has 1 + 2 + 4 + 8 = 15 nodes, and the 8 leaves at the deepest level are the answers. The inner nodes repeat partial solutions such as [1] because "exclude" leaves the path unchanged.
This tracer builds a new list with path + [nums[i]], so it never has to undo anything. Later chapters switch to a single shared list that is modified and then restored, which avoids the copying cost.
Model B: Pick the Next Element
At each node, choose which element comes next, but only from positions after the last one chosen. Every node is a distinct subset, so there are exactly 2^n nodes and every node is an answer.
You can confirm the node count by writing the tree's shape as a recurrence:
def count_pick_next(n, start=0):
# this node, plus one subtree for each element we could pick next
return 1 + sum(count_pick_next(n, i + 1) for i in range(start, n))
for n in range(6):
print(n, count_pick_next(n), 2 ** n)
# 0 1 1
# 1 2 2
# 2 4 4
# 3 8 8
# 4 16 16
# 5 32 32Both models give the same answers, but they have different shapes:
| Property | Include/exclude | Pick next |
|---|---|---|
| Branching factor | Always 2 | Varies from n down to 0 |
| Depth | Exactly n | At most n |
| Total nodes | 2^(n+1) − 1 | 2^n |
| Where answers live | Leaves only | Every node |
| Natural fit | Problems with a yes/no choice per item | Combinations, ordered "next item" choices |
The choice of model affects how easy it is to prune, how easy it is to avoid duplicates, and how many nodes you visit. You should pick the model on purpose.
Depth-First Order and Memory
Backtracking visits the tree depth-first. It follows one branch all the way down before trying a sibling. In the tracer output above, indentation shows depth, and the lines appear in exactly the order the calls happen.
As a result, the call stack holds only the path from the root to the current node and never the whole tree. The tree for subsets of 30 elements has over a billion nodes, but at any moment only about 31 frames are live. The extra space is O(depth) plus whatever each frame stores, while the time grows with the total number of nodes. Separating these two quantities is the starting point for the complexity chapter later on.
A Tree With Fixed Depth: Permutations
For permutations of n distinct items, depth k means "the first k positions are filled." The root has n children, each of those has n − 1, and so on, giving n! leaves. The inner nodes add to the cost:
def count_perm_nodes(n, depth=0):
if depth == n:
return 1
return 1 + (n - depth) * count_perm_nodes(n, depth + 1)
print(count_perm_nodes(3)) # 16 = 1 + 3 + 6 + 6
print(count_perm_nodes(8)) # 109601, versus 8! = 40320 leavesThe total stays below e · n!, so the leaves dominate the count, but the inner nodes are not free. If each node copies an n-length list, the work is multiplied by n.
Dead Nodes and Pruning
Most real problems have constraints, which are rules a valid answer must follow. A constraint turns some nodes into dead nodes: partial solutions that cannot be extended to any valid answer. When the search reaches a dead node it returns immediately, and that discards the entire subtree below it. This is called pruning.
Consider picking numbers from [2, 3, 5], without reuse, whose sum is exactly 5. In the pick-next tree, the node [2, 5] has sum 7. It is dead, and since all inputs are positive, every extension of it is dead too. Recognizing a dead node one level earlier can remove a subtree of any size, which is why the place where you put a check matters so much. A later chapter covers pruning in depth. For now, keep this idea in mind: a check placed at a node removes that node's whole subtree.
Designing a Tree Before Writing Code
Answer these four questions on paper first. Each answer maps directly to a piece of the recursive function.
| Question | Becomes in code | Subsets (pick next) | Permutations |
|---|---|---|---|
| What does a node represent? | Function parameters plus shared state | Chosen items, next start index | Filled positions, used items |
| What are the edges out of a node? | The `for` loop | Each index from `start` to `n − 1` | Each unused item |
| When is a node a solution? | The recording or base-case check | Always | When `len(path) == n` |
| When is a node dead? | An early `return` or `continue` | Never, for plain subsets | Never, for plain permutations |
Common modeling errors show up as wrong answers that you can predict from the tree:
- Duplicate results: two different paths lead to the same answer. For example,
[1, 2]and[2, 1]both appear in a subsets search because the edges were not restricted to later indices. - Missing results: an edge was left out, or a dead-node check was too aggressive.
- Infinite recursion: an edge does not move toward a leaf. For example, the start index never increases and reuse is not bounded by a target.
If you can draw the first two levels of your tree and point to where each answer appears exactly once, the code usually follows.
Exercise
For the include/exclude model of subsets of n elements, how many nodes does the tree have, and how many are answers? Check your formula against the tracer output for n = 3.
Show answer
The tree has 1 + 2 + 4 + ... + 2^n = 2^(n+1) − 1 nodes, and only the 2^n leaves at depth n are answers. For n = 3, that gives 15 nodes and 8 answers, which matches the 15 printed lines, 8 of them at the deepest indentation.
Exercise
You want all 2-element combinations of [1, 2, 3, 4]. Using the pick-next model, describe the nodes, edges, solution condition, and dead-node condition, and state how many leaves the tree has if you stop at depth 2.
Show answer
A node is a list of chosen items plus the next start index. The edges pick any index from start to 3. A node is a solution when it holds 2 items, and at that point you record it and return. A node is dead when too few elements remain to fill the remaining slots. For example, [4] with start 4 cannot be extended, and you can prune it by requiring n − start ≥ slots still needed. Stopping at depth 2 gives C(4, 2) = 6 solution leaves: [1,2], [1,3], [1,4], [2,3], [2,4], [3,4].
Exercise
Someone generates subsets by letting every node choose any element not already in the path, at any index. What goes wrong, and how does the tree show it?
Show answer
The same subset is reached along several paths. For example, {1, 2} is reached through 1 then 2 and through 2 then 1, so results are duplicated. The tree has the permutation shape, with on the order of n! nodes, instead of 2^n. Restricting the edges to indices after the last chosen one gives every subset exactly one path.