Sub topic 1
Recursion and the Call Stack, Revisited
Prerequisites
This chapter assumes you can write Python functions and loops, and that you know basic recursion with base cases. It also assumes you know lists, sets, and Big-O notation.
Recursion and the Call Stack
Each recursive call gets its own stack frame, which holds that call's local variables. When a call returns, its frame is removed and execution continues in the caller at the point right after the call. Backtracking depends on this behavior. Returning from a call is how the search steps back to an earlier decision.
Thinking in State-Space Trees
A state-space tree is a tree in which each node is a partial solution and each edge is one choice. The root is the empty solution. Backtracking is a depth-first walk of this tree. It goes deep along one branch, returns, and then tries the next sibling.
The Choose, Explore, Unchoose Template
Every backtracking function in this tutorial repeats three steps for each available option:
- Choose: add the option to the current partial solution.
- Explore: recurse to extend that solution further.
- Unchoose: remove the option so the next sibling starts from the same state.
Undoing Changes and Copying Results Correctly
Most solutions use one shared path list and change it in place. Two rules follow from that:
- Every change needs a matching undo. Here, each
appendis paired with apop. - When you record a result, save a copy with
path[:]. If you appendpathitself, every entry inresultis the same list object, and that list is empty by the time the search ends.
Generating All Subsets
Each call records the current path and then extends it only with later elements, so each subset appears exactly once.
def subsets(nums):
result = []
path = []
def backtrack(start):
result.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i]) # choose
backtrack(i + 1) # explore
path.pop() # unchoose
backtrack(0)
return result
print(subsets([1, 2, 3]))
# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]An input of size n has 2^n subsets, and copying each one costs up to O(n), so the total time is O(n · 2^n). The recursion depth is at most n.
Exercise
In subsets, what does the function return for [1, 2, 3] if you replace result.append(path[:]) with result.append(path)?
Show answer
It returns [[], [], [], [], [], [], [], []]. All eight entries refer to the same list object, and every append on that list is undone by a pop, so the list is empty when the search finishes.
Exercise
Why does the recursive call pass i + 1 rather than start + 1?
Show answer
Passing i + 1 means later calls only consider elements after the one just chosen. That keeps each subset in index order and stops the same subset from being produced twice, for example as both [1, 2] and [2, 1].