Sub topic 15
Backtracking Without Recursion
This chapter assumes you already know the choose-explore-unchoose template and the recursive subsets function from earlier chapters. You should also be comfortable with Python lists used as stacks, through append and pop.
Why Replace Recursion
A recursive backtracking function uses the call stack to remember two things for each level: where its loop stopped and what it changed. You can store the same information in a list you manage yourself. There are three practical reasons to do this:
- Python's default recursion limit is about 1000 frames. A search that goes deeper raises
RecursionError. - With an explicit stack, you can pause the search, inspect it, or stop it early without unwinding many nested calls.
- Some environments discourage deep recursion or don't support it.
The cost is clarity. The recursive version reads like the problem. The iterative version reads like bookkeeping.
What a Frame Must Remember
In the recursive subsets, each call has one local variable that matters, the loop index i. The shared path holds the choices made so far. So an explicit stack only needs one integer per level: the next index that level should try.
The Iterative Subsets Generator
def subsets_iterative(nums):
result = [[]] # the root records the empty subset
path = []
stack = [0] # stack[d] = next index to try at depth d
while stack:
i = stack[-1]
if i < len(nums):
stack[-1] = i + 1 # this frame's loop moves forward
path.append(nums[i]) # choose
result.append(path[:])
stack.append(i + 1) # explore: child starts after i
else:
stack.pop() # this frame's loop is finished
if path:
path.pop() # unchoose the element that led here
return result
print(subsets_iterative([1, 2, 3]))
# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]The output order matches the recursive version exactly, because the loop visits the state-space tree in the same depth-first order. The invariant len(path) == len(stack) - 1 always holds. That's why popping a frame also pops one element from the path, except at the root, where the path is already empty.
Two Styles of Explicit Stack
| Style | Frame contents | Undo step | Memory |
|---|---|---|---|
| Shared path (above) | Next index only | `path.pop()` when a frame ends | O(n) for the stack and path |
| Copied state | Index plus its own copy of the path | None needed | O(n) per frame, more in total |
The copied-state style pushes tuples like (start, path + [x]). Because no state is shared, it can't suffer the restoration bugs covered earlier. It allocates a new list at every node, though.
Exercise
Modify subsets_iterative so it returns only the subsets of exactly k elements, and skips pushing frames that cannot reach size k.
Show answer
Record only when len(path) == k, and treat a frame as finished when i >= len(nums) or len(path) == k. Change the condition to if i < len(nums) and len(path) < k: and record with if len(path) == k: result.append(path[:]). Start with result = [[]] if k == 0 else []. The else branch stays the same, so the path is still undone when each frame ends.