Created
June 4, 2020 03:33
-
-
Save bhaveshmunot1/1b12ccd13405aeb6bfb1d8e62e7131ed to your computer and use it in GitHub Desktop.
Find Nth Fibonacci Number using Dynamic Programming (Memoization Approach)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
map<int, int> memory; // for storing precomputed answers. | |
int fibonacci(int n) { | |
if (memory.find(n) != memory.end()) { // if already exists. | |
return memory[n]; // just return the precomputed value. | |
} | |
// Find the n_th Fibonacci number and make a note of it in memory. | |
memory[n] = fibonacci(n-1) + fibonacci(n-2); | |
return memory[n]; | |
} | |
int n_th_fibonacci(int n) { | |
memory[1] = 0; // base case that we already know. | |
memory[2] = 1; // base case that we already know. | |
return fibonacci(n); // find answer. | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment