Counting with Dynamic Programming
Closed formulas like cover the textbook cases. Real counting problems have obstacles, constraints and odd shapes: grid paths around blocked cells, strings that avoid a pattern, ways to climb stairs with given step sizes. The general method is to find a recurrence by splitting on the last (or first) step, then compute it bottom-up with dynamic programming (DP). Counting with DP is the sum rule applied over and over, with results stored so nothing is counted twice.
The recipe
- Define = the number of ways to reach (or complete) that state.
- Split on the last move: over all possible previous states (sum rule, since the cases are disjoint).
- Fix the base cases.
- Compute in an order where every needed value is ready (a topological order of the state graph).
This works whenever the states form a DAG: counting paths in a DAG is the universal form of the method.
Grid paths with obstacles
Paths from the top-left to the bottom-right of a grid, moving only right or down, avoiding blocked cells. Without obstacles the count is ; with obstacles there is no formula, but the DP is two lines:
from math import comb
grid = [
"....#...",
"..#.....",
"......#.",
".#......",
"....#...",
]
R, C = len(grid), len(grid[0])
ways = [[0] * C for _ in range(R)]
for r in range(R):
for c in range(C):
if grid[r][c] == "#":
continue
if r == 0 and c == 0:
ways[r][c] = 1
else:
ways[r][c] = (ways[r - 1][c] if r else 0) + (ways[r][c - 1] if c else 0)
print("paths avoiding obstacles:", ways[R - 1][C - 1])
print("without obstacles:", comb(R + C - 2, R - 1))paths avoiding obstacles: 55
without obstacles: 330
Climbing stairs and compositions
How many ways can you climb stairs taking 1, 2 or 3 steps at a time? Split on the last step: with (the empty climb). These are the tribonacci numbers. Changing the allowed steps changes only the sum.
def climbs(n, steps):
f = [1] + [0] * n
for i in range(1, n + 1):
f[i] = sum(f[i - s] for s in steps if s <= i)
return f
print("steps {1,2}: ", climbs(10, [1, 2]))
print("steps {1,2,3}:", climbs(10, [1, 2, 3]))
print("steps {2,5}: ", climbs(10, [2, 5]))steps {1,2}: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
steps {1,2,3}: [1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274]
steps {2,5}: [1, 0, 1, 0, 1, 1, 1, 2, 1, 3, 2]
With steps we get Fibonacci numbers, as in the domino tilings. Order matters here (1+2 and 2+1 are different climbs), unlike the coin-change count of Generating Functions, where only the multiset of coins matters. The difference is the loop order: coins in the outer loop count combinations, totals in the outer loop count sequences.
Counting strings that avoid a pattern
How many strings of length over do not contain "ab"? Track the last character as the state: = valid strings ending in "a", = valid strings ending in something else. Appending "b" after "a" is forbidden:
(after an "a" only "c" is allowed among the non-"a" letters; otherwise "b" and "c" both are).
from itertools import product
def avoid_ab(n):
e, o = 1, 2 # length 1: "a" | "b", "c"
for _ in range(n - 1):
e, o = e + o, e + 2 * o
return e + o
brute = lambda n: sum(1 for s in product("abc", repeat=n) if "ab" not in "".join(s))
print([avoid_ab(n) for n in range(1, 9)])
print([brute(n) for n in range(1, 9)])[3, 8, 21, 55, 144, 377, 987, 2584]
[3, 8, 21, 55, 144, 377, 987, 2584]
This "state machine plus counting" idea is how regular-expression and automaton-based counting works in general: the number of accepted strings of length is an entry of the -th power of the automaton's transition matrix (walks in digraphs).
In software
Counting DP shows up in combinatorics libraries, in probability computations (replace counts by probabilities), in parsing (counting parse trees), in bioinformatics (sequence alignments) and in interview problems. When counts get huge, contest problems ask for the answer modulo a prime like ; modular arithmetic lets you reduce after every addition. See Memoization and Tabulation in the DSA course for the general technique.
Exercises
Exercise 1: A 3 × 3 grid
How many right/down paths cross a grid of cells from top-left to bottom-right if the centre cell is blocked?
Answer
Solution
Without the block there are paths. Paths through the centre: (2 ways in, 2 ways out). : along the top edge then down the right edge, or down the left edge then along the bottom.
Exercise 2: Stairs with steps 1 and 3
Count the ways to climb 7 stairs with steps of 1 or 3.
Answer
Solution
, : , , , , .
Exercise 3: Counting modulo a prime (code)
Count the right/down paths across a grid of points (from corner to corner) modulo , by DP, and check it against .
Answer
Both computations give the same residue.
Solution
A rolling one-dimensional array keeps memory at : after processing row , row[c] holds the number of paths to point .
from math import comb
MOD = 10 ** 9 + 7
n = 1000
row = [1] * n
for r in range(1, n):
for c in range(1, n):
row[c] = (row[c] + row[c - 1]) % MOD
print(row[-1], comb(2 * n - 2, n - 1) % MOD)965601742 965601742
Test yourself
Counting DP mainly applies which counting rule repeatedly?
- The division rule
- The sum rule over disjoint last steps
- The pigeonhole principle
- Inclusion-exclusion
With steps of 1 or 2, how many ways are there to climb 5 stairs?
- 5
- 8
- 10
- 13
Counting paths in a graph with DP requires the graph of states to be…
- complete
- a DAG (no cycles)
- bipartite
- planar