TExcelTAD
Home › Discrete Mathematics › Counting with Dynamic Programming

Counting with Dynamic Programming

Closed formulas like (nk)\binom{n}{k} 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

  1. Define f(state)f(\text{state}) = the number of ways to reach (or complete) that state.
  2. Split on the last move: f(state)=∑f(previous state)f(\text{state}) = \sum f(\text{previous state}) over all possible previous states (sum rule, since the cases are disjoint).
  3. Fix the base cases.
  4. 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 (r+c−2r−1)\binom{r + c - 2}{r - 1}; with obstacles there is no formula, but the DP is two lines:

python · try it yourself
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 nn stairs taking 1, 2 or 3 steps at a time? Split on the last step: f(n)=f(n−1)+f(n−2)+f(n−3)f(n) = f(n-1) + f(n-2) + f(n-3) with f(0)=1f(0) = 1 (the empty climb). These are the tribonacci numbers. Changing the allowed steps changes only the sum.

python · try it yourself
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 {1,2}\{1, 2\} 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 nn over {a,b,c}\{a, b, c\} do not contain "ab"? Track the last character as the state: e(n)e(n) = valid strings ending in "a", o(n)o(n) = valid strings ending in something else. Appending "b" after "a" is forbidden:

e(n)=e(n−1)+o(n−1),o(n)=e(n−1)⋅1+o(n−1)⋅2e(n) = e(n-1) + o(n-1), \qquad o(n) = e(n-1) \cdot 1 + o(n-1) \cdot 2

(after an "a" only "c" is allowed among the non-"a" letters; otherwise "b" and "c" both are).

python · try it yourself
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 nn is an entry of the nn-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 109+710^9 + 7; 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 3×33 \times 3 grid of cells from top-left to bottom-right if the centre cell is blocked?

Answer
Solution

Without the block there are (42)=6\binom{4}{2} = 6 paths. Paths through the centre: (21)⋅(21)=4\binom{2}{1} \cdot \binom{2}{1} = 4 (2 ways in, 2 ways out). 6−4=26 - 4 = 2: 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

f(n)=f(n−1)+f(n−3)f(n) = f(n-1) + f(n-3), f(0)=f(1)=f(2)=1f(0) = f(1) = f(2) = 1: f(3)=2f(3) = 2, f(4)=3f(4) = 3, f(5)=4f(5) = 4, f(6)=6f(6) = 6, f(7)=9f(7) = 9.

Exercise 3: Counting modulo a prime (code)

Count the right/down paths across a 1000×10001000 \times 1000 grid of points (from corner to corner) modulo 109+710^9 + 7, by DP, and check it against (1998999) mod (109+7)\binom{1998}{999} \bmod (10^9 + 7).

Answer

Both computations give the same residue.

Solution

A rolling one-dimensional array keeps memory at O(n)O(n): after processing row rr, row[c] holds the number of paths to point (r,c)(r, c).

python · try it yourself
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?

  1. The division rule
  2. The sum rule over disjoint last steps
  3. The pigeonhole principle
  4. Inclusion-exclusion

With steps of 1 or 2, how many ways are there to climb 5 stairs?

  1. 5
  2. 8
  3. 10
  4. 13

Counting paths in a graph with DP requires the graph of states to be…

  1. complete
  2. a DAG (no cycles)
  3. bipartite
  4. planar