File tree Expand file tree Collapse file tree 1 file changed +17
-7
lines changed
24 - Dynamic Programming Problems/01 - Example | Nth Fibonacci Number Expand file tree Collapse file tree 1 file changed +17
-7
lines changed Original file line number Diff line number Diff line change 11class Solution {
22 public:
33 int nthFibonacci (int n) {
4- vector<int > dp (n+1 , -1 );
5-
6- if (n == 1 || n == 0 ) return n;
7- if (dp[n] != -1 ) return dp[n];
8-
9- dp[n] = nthFibonacci (n-1 ) + nthFibonacci (n-2 );
10-
4+ // Create a vector to store computed Fibonacci values, initialized to -1.
5+ // This is used for memoization to avoid redundant calculations.
6+ vector<int > dp (n + 1 , -1 );
7+
8+ // Base case: If n is 0 or 1, the Fibonacci value is n itself.
9+ if (n == 0 || n == 1 )
10+ return n;
11+
12+ // Check if the value for the nth Fibonacci number is already computed.
13+ // If dp[n] is not -1, it means the value is already stored in the memoization table.
14+ if (dp[n] != -1 )
15+ return dp[n];
16+
17+ // Recursive case: Compute the nth Fibonacci number by summing the (n-1)th and (n-2)th numbers.
18+ dp[n] = nthFibonacci (n - 1 ) + nthFibonacci (n - 2 );
19+
20+ // Store the computed value in dp[n] and return it.
1121 return dp[n];
1222 }
1323};
You can’t perform that action at this time.
0 commit comments