Skip to content

Commit 797f1f6

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent 613a826 commit 797f1f6

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)