We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 613a826 commit 797f1f6Copy full SHA for 797f1f6
24 - Dynamic Programming Problems/01 - Example | Nth Fibonacci Number/03 - Bottom-Up | DP | Approach.cpp
@@ -0,0 +1,22 @@
1
+class Solution {
2
+ public:
3
+ int nthFibonacci(int n) {
4
+ // Create a vector to store Fibonacci numbers up to the nth term.
5
+ // The size is n+1 because we want to include the 0th term.
6
+ vector<int> dp(n + 1);
7
+
8
+ // Base cases of the Fibonacci sequence:
9
+ dp[0] = 0; // F(0) = 0
10
+ dp[1] = 1; // F(1) = 1
11
12
+ // Use a loop to calculate Fibonacci numbers from F(2) to F(n).
13
+ for (int i = 2; i <= n; i++) {
14
+ // The nth Fibonacci number is the sum of the two preceding numbers:
15
+ // F(i) = F(i-1) + F(i-2)
16
+ dp[i] = dp[i - 1] + dp[i - 2];
17
+ }
18
19
+ // Return the nth Fibonacci number.
20
+ return dp[n];
21
22
+};
0 commit comments