Dynamic programming
The pure recursive Fibonacci function from the Recursive Fibonacci lesson results in exponential number of calls. We can avoid duplicate call by using memoization, which results in linear number of calls.
Memoization works by storing the value already computed in a memo. The memo can be made using a vector
, a map
, an unordered_map
, etc. When a previously computed value is needed, repeat calculation can be avoided by using the value in the memo.
Define the function int fibonacci(int n, std::vector &memo)
which gives the nth Fibonacci number by using recursion and memoization.