awelgorithms

Memoize a recursive solution

Updated

Plain recursive fib recomputes the same subproblems exponentially many times. A cache keyed by n turns each state into one computation: check the cache, compute once, store, return.

What to focus on

The recurrence stays the same. Only the store changes. fib(30) takes over a million calls without the cache and 31 with it.

Worked examples

ten

n = 10
  1. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

Result: 55

one

n = 1
  1. base case

Result: 1

thirty

n = 30
  1. cached: 31 computations

Result: 832040

Try it

Write fibMemo(n). n is a non-negative integer. Return fib(n) with a recursive definition and a cache so each n is computed once. On 10 return 55. On 1 return 1. On 30 return 832040.

n is a non-negative integer no larger than 50.