Sub topic 4
Defining the state, recurrence, and base cases
This chapter assumes you can write recursive functions in Python, read Big-O notation, and use tuples and dictionaries. It also builds on the two previous chapters. A problem suits dynamic programming (DP) when its subproblems repeat (overlapping subproblems) and when the best answer can be built from the best answers to smaller pieces (optimal substructure). Those properties tell you that DP can work. This chapter covers the step that makes it work: writing a precise specification of the subproblems. Memoization and tabulation, covered in the next two chapters, are just two ways to evaluate that specification.
A DP specification has four parts:
| Part | Question it answers | Fibonacci example |
|---|---|---|
| State | Which parameters identify one subproblem? | `n` |
| Meaning | In words, what value does a state stand for? | `F(n)` is the n-th Fibonacci number |
| Recurrence | How is a state's value computed from smaller states? | `F(n) = F(n-1) + F(n-2)` |
| Base cases | Which states are answered directly, without recursion? | `F(0) = 0`, `F(1) = 1` |
Add a fifth line, the goal state: the state whose value answers the original question. For Fibonacci the goal state is just F(n). In other problems it is less obvious.
The state: what you need to know about the rest of the problem
A state is the smallest set of values that fully describes a remaining subproblem. "Fully" means the answer depends only on those values and not on how you got there. If two different paths through the problem lead to the same state, the remaining work must be the same for both. That property is what makes caching a state's answer correct.
A useful way to find the state is to imagine you are partway through solving the problem by making decisions one at a time. Ask: what must I remember to make the rest of the decisions correctly? Whatever you must remember goes in the state. Anything you could forget without changing the answer stays out.
Common shapes of state:
| Problem input | Typical state | Example |
|---|---|---|
| One number | That number, shrinking | Fibonacci, coin change on an amount |
| One sequence | An index (a prefix or suffix) | Maximum sum of non-adjacent elements |
| Two sequences | A pair of indices | Longest common subsequence |
| A grid | A cell `(row, col)` | Counting paths |
| Items plus a budget | Item index and remaining budget | 0/1 knapsack |
| Any of the above with a rule about history | Add a field recording the relevant history | "Last move", "number used so far" |
Write the meaning in a full sentence
Before writing a recurrence, write a sentence of the form "f(state) is the ... of ... given ...". For example: "ways(n) is the number of distinct step sequences that climb exactly n remaining stairs." Many DP bugs come from a vague meaning. Without the sentence, it's unclear whether n means stairs climbed or stairs remaining, or whether i means "up to and including index i" or "before index i". The sentence settles these questions, and every later line of code should agree with it.
The recurrence: decide one thing, then recurse
A recurrence expresses a state's value in terms of strictly smaller states. The usual recipe is to look at one decision, normally the first or last choice, and list every option for it:
- Enumerate the options for this decision.
- For each option, find the state that remains after taking it.
- Combine the results with the operation that fits the question:
+for counting,minormaxfor optimizing,orfor feasibility.
Take the classic stairs problem: you climb n stairs taking 1 or 2 steps at a time. How many distinct sequences reach the top?
- Decision: the size of the next step.
- Options: 1 (leaves
n-1stairs) or 2 (leavesn-2stairs). - Combine: the options lead to disjoint sets of sequences, so add them.
ways(n) = ways(n-1) + ways(n-2)
The options must be exhaustive, so that every solution is covered, and for counting problems they must also be disjoint, so that no solution is counted twice. For min and max, overlap is harmless, but missing an option still gives a wrong answer.
Base cases: the smallest states and the invalid ones
Base cases are states whose values you return directly. They come in two kinds:
- Smallest valid states. For stairs,
ways(0) = 1. There is exactly one way to climb zero stairs: the empty sequence. Returning 0 here is a common mistake, and it makes every count zero. - Invalid states. A 2-step with only one stair left would lead to
ways(-1). You either return a neutral value for it (0 for counting, infinity for minimizing, negative infinity for maximizing) or check before recursing so that you never reach it.
Check base cases against the meaning sentence, not against intuition. "The number of sequences that climb exactly 0 stairs" is clearly 1.
When the obvious state is not enough
Now add a rule: you may not take two 2-steps in a row. The state n alone no longer describes the remaining problem. With 4 stairs left, the next step can be a 2-step if your last step was a 1-step, but not if it was a 2-step. Two paths reach "4 stairs left" with different futures, so n violates the definition of a state.
The fix is to augment the state with the missing history: ways(n, last), where last is the size of the previous step (0 at the start).
Meaning: "ways(n, last) is the number of valid sequences that climb exactly n remaining stairs, given that the previous step had size last."
Recurrence:
- A 1-step is always allowed and leads to
ways(n-1, 1). - A 2-step is allowed when
n >= 2andlast != 2, and leads toways(n-2, 2).
Goal state: ways(n, 0).
The code below writes the recurrence as plain recursion and checks it against a brute-force enumeration. Checking a new recurrence against brute force on small inputs is the most reliable way to catch a wrong state or a missed option before you make it fast.
def count_brute(n, ok):
"""Enumerate every sequence of 1s and 2s summing to n; count those passing ok."""
def gen(remaining, path):
if remaining == 0:
yield path
return
for step in (1, 2):
if step <= remaining:
yield from gen(remaining - step, path + [step])
return sum(1 for seq in gen(n, []) if ok(seq))
def no_double_two(seq):
return all(not (a == 2 and b == 2) for a, b in zip(seq, seq[1:]))
def ways(n, last):
# Base case: zero stairs remaining -> the empty sequence.
if n == 0:
return 1
total = ways(n - 1, 1) # option: take a 1-step
if n >= 2 and last != 2: # option: take a 2-step, if allowed
total += ways(n - 2, 2)
return total
for n in range(12):
assert ways(n, 0) == count_brute(n, no_double_two), n
print([ways(n, 0) for n in range(12)])Running it prints [1, 1, 2, 3, 4, 6, 9, 13, 19, 28, 41, 60], and every assertion passes.
The diagram shows which states ways(4, 0) depends on. State (2, 1) is reached along two different paths. That is the overlapping subproblem that memoization will exploit in the next chapter.
Augmenting the state has a cost. The number of states becomes the product of the ranges of each field. Here that is about 3n, which is cheap. Adding a field such as "the set of items used so far" can make the state space exponential. Add only what the future actually depends on.
A two-parameter example: grid paths with obstacles
Count the paths from the top-left to the bottom-right of a grid, moving only right or down, without entering blocked cells.
- State:
(r, c), a cell. - Meaning: "
paths(r, c)is the number of valid paths from(0, 0)to(r, c)." - Recurrence: the last move into
(r, c)came from above or from the left, sopaths(r, c) = paths(r-1, c) + paths(r, c-1). - Base cases: out of bounds gives 0, a blocked cell gives 0, and
paths(0, 0) = 1if that cell is open. - Goal:
paths(rows-1, cols-1).
Here the decision is the last move, not the first. Both directions work as long as the meaning sentence matches. A "first move" version would define paths(r, c) as the number of paths from (r, c) to the goal.
def count_paths(grid):
rows, cols = len(grid), len(grid[0])
def paths(r, c):
if r < 0 or c < 0: # invalid state: off the grid
return 0
if grid[r][c] == 1: # invalid state: blocked cell
return 0
if r == 0 and c == 0: # smallest valid state
return 1
return paths(r - 1, c) + paths(r, c - 1)
return paths(rows - 1, cols - 1)
grid = [
[0, 0, 0],
[0, 1, 0],
[0, 0, 0],
]
print(count_paths(grid)) # 2The order of the checks matters. The blocked-cell check comes before the (0, 0) check, so a blocked start correctly returns 0.
The design process
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Answers too large in a counting problem | Options overlap, so solutions are counted twice | Make each option lead to a disjoint set of solutions |
| Answers too small or zero | Missing option, or the base case returns 0 where it should return 1 | Recheck the option list and the empty-solution base case |
| Correct on some inputs, wrong on others | State is missing history the future depends on | Augment the state |
| `RecursionError` or an infinite loop | Some option doesn't shrink the state, or no base case covers the edge | Check that every option moves toward a base case |
| `IndexError` | Invalid states are reached without a guard | Return a neutral value or check bounds before recursing |
| A minimum comes out as 0 | Invalid state returns 0 inside a `min` | Return `float('inf')` for invalid states when minimizing |
| Off-by-one answers | Meaning sentence is ambiguous (inclusive or exclusive index) | Rewrite the sentence and make the code match it |
Exercise
You are given a list of house values and may rob any houses except two adjacent ones. Define a state, its meaning sentence, the recurrence, the base cases, and the goal state for the maximum total you can rob.
Show answer
State: an index i. Meaning: best(i) is the maximum total obtainable from houses 0 through i inclusive. Recurrence: best(i) = max(best(i-1), best(i-2) + values[i]). Either skip house i, or rob it and skip house i-1. Base cases: best(i) = 0 for i < 0, which covers best(-1) and best(-2). Goal: best(len(values) - 1), which is 0 for an empty list.
Exercise
In the stairs problem, a new rule forbids three 1-steps in a row (2-steps are unrestricted). Is ways(n, last) a sufficient state? If not, what state would you use, and what is the recurrence?
Show answer
It is not sufficient, because after a 1-step you also need to know whether the step before it was a 1-step. Use ways(n, ones), where ones is the number of consecutive 1-steps just taken (0, 1, or 2). Recurrence: a 1-step is allowed when ones < 2 and leads to ways(n-1, ones+1). A 2-step is allowed when n >= 2 and leads to ways(n-2, 0). Base case: ways(0, ones) = 1. Goal: ways(n, 0).
Exercise
For the fewest coins needed to make an amount, a student writes best(a) = 1 + min(best(a - c) for each coin c) with best(0) = 0, and returns 0 for negative a. What goes wrong, and how do you fix it?
Show answer
Returning 0 for a negative amount makes an overshooting coin look free. For example, with coins [5] and a = 3, the formula gives best(3) = 1 + best(-2) = 1, which is wrong. Invalid states in a minimization must return float('inf'). Alternatively, consider only coins c <= a and return infinity when no coin fits, then map an infinite final answer to -1.