Tiling a 2×n board
Instead of recursing top-down with a cache, build the answer bottom-up in a plain array. About 10 minutes.
A different puzzle with a familiar answer
Picture a long, narrow hallway floor, 2 tiles tall and n tiles long, and a pile of dominoes that each cover two tiles. A domino can stand upright and fill one column, or two can lie flat, one on top of the other, and fill two columns. How many ways can you cover the whole floor?
Use the stairs trick: look at the far end. Either one upright domino covers the last column, leaving a floor one shorter, or two flat dominoes cover the last two columns, leaving a floor two shorter.
Fill a table from the small end
This time, skip the recursion entirely. Start with the answers you already know: an empty floor can be covered in exactly 1 way (do nothing), and a floor 1 tile long in exactly 1 way (one upright domino).
Then work out length 2, then length 3, and so on, each from the two answers just before it. When you reach length n, the answer is waiting for you. No repeated questions and no notebook lookups, just a row filled in from left to right. This is called tabulation, or bottom-up DP.
ways = [0] * (n + 1)
ways[0] = 1
if n >= 1:
ways[1] = 1
for i in range(2, n + 1):
ways[i] = ways[i - 1] + ways[i - 2]
return ways[n]Start from what we know: an empty board has 1 tiling (do nothing), and a 2 × 1 board has 1 (one upright domino).
You're filling the table from the left. What must already be filled in before you work out the answer for length 5?
- AThe answers for lengths 4 and 3
- BThe answer for length 6
Show the answer
The answers for lengths 4 and 3. You fill left to right, so both are already there when you reach length 5.
Tiling a 2×n board
You have a 2×n board and an unlimited supply of 1×2 dominoes, which can be placed upright (covering one column) or lying flat (covering two columns, one on top of the other). Return the number of distinct ways to fully tile the board.
n = 3 → 3
0 ≤ n ≤ 75