File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
24 - Dynamic Programming Problems/03 - Climbing Stairs Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments