Advertisement
Guest User

Memoizing Fibonacci

a guest
Nov 1st, 2014
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 KB | None | 0 0
  1. // This is the canonical recursive definition of the Fibonacci function
  2. int fib(int n)
  3. {
  4.     // First check the base case, the sequence always starts 0, 1
  5.     if(n < 2) return n;
  6.     return fib(n-1) + fib(n-2);
  7. }
  8.  
  9. // Here's a memoized version
  10. std::map<int, int> fib_memo;
  11. int fib(int n)
  12. {
  13.     // First check the base case, the sequence always starts 0, 1
  14.     if(n < 2) return n;
  15.     // Then check to see if we've evaluated this one before -- if so, use that
  16.     if(fib_memo.count(n)) return fib_memo[n];
  17.     // Otherwise, calculate the value and store it before returning it
  18.     int value = fib(n-1) + fib(n-2);
  19.     fib_memo[n] = value;
  20.     return value;
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement