Skip to content

Commit f2af4e7

Browse files
authored
Update 02 - Top-Down | DP | Approach.cpp
1 parent ad20963 commit f2af4e7

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed
Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
11
class 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
};

0 commit comments

Comments
 (0)