Problem. How many ways are there to climb stairs taking 1 or 2 steps at a time?

β€” the Fibonacci numbers, shifted: .

long long stairs(int n) {
    long long a = 1, b = 1;
    for (int i = 2; i <= n; i++) { long long c = a + b; a = b; b = c; }
    return b;
}

The generalisations

Steps allowedRecurrenceSequence
Fibonacci
Tribonacci
sum of the last -bonacci; with a sliding sum
Arbitrary set coin change permutations
With costs instead of shortest path on a line
Cannot use the same step twice in a rowadd a β€œlast step” dimension
Some steps are brokenskip those states

For , keep a running window sum so each term is :

long long window = 0;
for (int i = 1; i <= n; i++) {
    window += f[i-1];
    if (i > k) window -= f[i-1-k];
    f[i] = window;
}

Huge β€” matrix exponentiation

All of these are linear recurrences, so matrix exponentiation handles up to in , or Kitamasa in .

For plain Fibonacci, fast doubling is best:

See Fibonacci Numbers.

Tiling problems β€” the same family

ProblemCount
Tile with dominoes
Tile with and
Tile with dominoes; 0 for odd
Tile with dominoes and L-trominoes
Tile , smallbroken profile DP,
Tile , huge profile DP + matrix power,
Binary strings with no two adjacent 1s
Subsets of with no two consecutive
Compositions of into parts

Domino tilings of being Fibonacci is the standard first example of β€œa counting problem with a linear recurrence”, and the derivation (the last column is either one vertical domino or two horizontal ones) is the model for every profile DP.

When there is no obvious recurrence

Compute the first 10-15 terms by brute force and:

  1. Check whether for small integer .
  2. Run Berlekamp-Massey to find the recurrence automatically.
  3. Search OEIS.

The combination β€” brute-force a few terms, Berlekamp-Massey, then Kitamasa β€” solves β€œcount the tilings of a board for ” without ever deriving the recurrence by hand. See Solving Linear Recurrences.

The Kasteleyn formula

For domino tilings of an arbitrary planar region, the count is a Pfaffian (hence a determinant) computable in polynomial time β€” the FKT algorithm. For a board:

Striking, and a reminder that counting perfect matchings is polynomial on planar graphs even though it is p-hard in general.

Why it is worth knowing

The staircase problem is the smallest interesting DP, and it is the entry point to a chain of increasingly powerful techniques applied to the same recurrence: iteration β†’ matrix power β†’ profile DP for 2D β†’ Berlekamp-Massey when the recurrence is unknown. Following that chain is a good way to learn all four.

See also: Fibonacci Numbers Β· Broken Profile DP Β· Matrix Exponentiation