Climbing stairs
Plain recursion recomputes the same smaller cases over and over; a cache remembers them instead. About 11 minutes.
Think about your very last step
You're at the bottom of a staircase with n stairs, and each move climbs 1 or 2 stairs. How many different ways can you reach the top?
Listing every route by hand gets messy fast. So flip it around and ask about the last move instead. To stand on the top stair, you either stepped up one from the stair just below, or jumped two from the stair below that. There's no other way in.
So the ways to reach the top are the ways to reach the stair below, plus the ways to reach the one below that.
def ways(n):
if n <= 1:
return 1
return ways(n - 1) + ways(n - 2)The same question, asked again and again
That code is correct, but give it 40 stairs and you'll be waiting a long time. Step through the calls below to see why.
Working out stair 4 asks about stair 3 and stair 2. But stair 3 asks about stair 2 again, completely from scratch. The smaller the stair, the more often it gets asked. For 40 stairs, the same handful of questions get answered hundreds of millions of times.
ways(4): the last move came from stair 3 or stair 2. So it asks ways(3) and ways(2).
Write the answer down the first time
The fix is what you'd do on paper: keep a notebook. Before working anything out, check whether the answer is already written down. If it is, use it. If not, work it out, write it down, and then return it.
Now each stair is solved exactly once, so 40 stairs means about 40 small additions instead of hundreds of millions. This trick is called memoization (from "memo", a note to yourself), and it's the heart of dynamic programming.
memo = {}
def ways(n):
if n <= 1:
return 1
if n not in memo:
memo[n] = ways(n-1) + ways(n-2)
return memo[n]Without a cache, how many times does plain recursion compute ways(2) while working out ways(6)?
- AMore than once
- BExactly once
Show the answer
More than once. ways(2) is needed by ways(3) and ways(4), which are both called separately, so ways(2) gets recomputed.
Climbing stairs
A staircase has n stairs. From any stair, you can move up by 1 or by 2. Return the number of distinct ways to go from the ground (stair 0) to stair n.
n = 4 → 5
0 ≤ n ≤ 48