Tiling with memoization
Tiles come in lengths 1, 2 and 3. How many different ordered ways can you cover a strip of length n?
The first tile placed leaves a smaller strip, so the answer is a sum of three smaller answers:
def ways(n):
if n < 0:
return 0
if n == 0:
return 1
return (ways(n - 1) + ways(n - 2)
+ ways(n - 3))That is correct but hopeless for large n. It solves the same strips over and over, and the calls grow exponentially.
Memoization
Save each answer the first time it is computed. functools.cache does this with one line:
from functools import cache
@cache
def f(n): ...A strip of length 0 has exactly one cover, which is placing nothing. A negative length has none.
Your task
Write tile_ways(n) returning the number of ordered ways to cover a strip of length n with tiles of lengths 1, 2 and 3, using recursion with memoization. It must return quickly for n = 60.
The explanation opens here once every check passes.