Now apply the memoization pattern to climbing stairs:
function climbStairs(n, dp)
if dp[n] ≠ -1 then
return dp[n]
if n = 1 then
return 1
if n = 2 then
return 2
dp[n] := climbStairs(n - 1, dp) + climbStairs(n - 2, dp)
return dp[n]
The structure is identical to memoized Fibonacci, just with adjusted base cases. This runs in time and space.
You've now applied the same memoization pattern to two different problems. Learn once, use everywhere. That's why patterns matter. Take time to work through examples. The pattern becomes clearer with practice. Compare the runtime to the naive version. The difference is dramatic even for small inputs.