Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This is the canonical recursive definition of the Fibonacci function
- int fib(int n)
- {
- // First check the base case, the sequence always starts 0, 1
- if(n < 2) return n;
- return fib(n-1) + fib(n-2);
- }
- // Here's a memoized version
- std::map<int, int> fib_memo;
- int fib(int n)
- {
- // First check the base case, the sequence always starts 0, 1
- if(n < 2) return n;
- // Then check to see if we've evaluated this one before -- if so, use that
- if(fib_memo.count(n)) return fib_memo[n];
- // Otherwise, calculate the value and store it before returning it
- int value = fib(n-1) + fib(n-2);
- fib_memo[n] = value;
- return value;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement