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 allowed | Recurrence | Sequence |
|---|---|---|
| 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 row | add a βlast stepβ dimension | |
| Some steps are broken | skip 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
| Problem | Count |
|---|---|
| Tile with dominoes | |
| Tile with and | |
| Tile with dominoes | ; 0 for odd |
| Tile with dominoes and L-trominoes | |
| Tile , small | broken 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:
- Check whether for small integer .
- Run Berlekamp-Massey to find the recurrence automatically.
- 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