Skip to content

Commit 6f8deaa

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent dc4ccda commit 6f8deaa

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public:
3+
// Function to calculate the number of ways to climb `n` stairs using dynamic programming
4+
int climbStairs(int n) {
5+
// Create a dp array where dp[i] will store the number of ways to reach the ith step
6+
vector<int> dp(n+1, 0);
7+
8+
// Base case: There's one way to reach the 0th step (by staying at the start)
9+
dp[0] = 1;
10+
11+
// Base case: If n >= 1, there's one way to reach the 1st step (by taking a single step)
12+
if(n >= 1) dp[1] = 1;
13+
14+
// Iterate from the 2nd step to the nth step
15+
for(int i = 2; i <= n; i++) {
16+
// The number of ways to reach step i is the sum of:
17+
// - the number of ways to reach step i-1 (taking 1 step)
18+
// - the number of ways to reach step i-2 (taking 2 steps)
19+
dp[i] = dp[i-1] + dp[i-2];
20+
}
21+
22+
// Return the number of ways to reach the nth step
23+
return dp[n];
24+
}
25+
};

0 commit comments

Comments
 (0)