File tree Expand file tree Collapse file tree 1 file changed +24
-0
lines changed
24 - Dynamic Programming Problems/03 - Climbing Stairs Expand file tree Collapse file tree 1 file changed +24
-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 optimized space
4+ int climbStairs (int n) {
5+ // Base cases: there's one way to stay at the 0th step (prev1) and one way to reach the 1st step (prev2)
6+ int prev1 = 1 ; // Represents the number of ways to reach the step (i-1)
7+ int prev2 = 1 ; // Represents the number of ways to reach the step (i-2)
8+
9+ // Iterate from step 2 to step n, calculating the number of ways to reach each step
10+ for (int i = 2 ; i <= n; i++) {
11+ // The number of ways to reach step i is the sum of the ways to reach step (i-1) and step (i-2)
12+ int curr = prev1 + prev2;
13+
14+ // Update prev2 to prev1 (step (i-2) becomes the previous step)
15+ prev2 = prev1;
16+
17+ // Update prev1 to curr (step (i-1) becomes the current step)
18+ prev1 = curr;
19+ }
20+
21+ // Return the number of ways to reach the nth step
22+ return prev1;
23+ }
24+ };
You can’t perform that action at this time.
0 commit comments