Skip to content

Commit ad19ebb

Browse files
authored
Create 04 - Space Optimized | DP | Approach.cpp
1 parent 6f8deaa commit ad19ebb

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
};

0 commit comments

Comments
 (0)