Skip to content

Commit 6243d9c

Browse files
authored
Updating 70.climbing_stairs.cpp
Updating the solution with a more easily understandable code according to the video solution
1 parent c50d6fa commit 6243d9c

File tree

1 file changed

+9
-19
lines changed

1 file changed

+9
-19
lines changed

cpp/neetcode_150/13_1-d_dynamic_programming/climbing_stairs.cpp

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Climbing stairs, either 1 or 2 steps, distinct ways to reach top
33
Ex. n = 2 -> 2 (1 + 1, 2), n = 3 -> 3 (1 + 1 + 1, 1 + 2, 2 + 1)
44
5-
Recursion w/ memoization -> DP, why DP? Optimal substructure
5+
Bottom-up DP
66
Recurrence relation: dp[i] = dp[i - 1] + dp[i - 2]
77
Reach ith step in 2 ways: 1) 1 step from i-1, 2) 2 steps from i-2
88
@@ -12,25 +12,15 @@
1212

1313
class Solution {
1414
public:
15+
//Fibonacci series : 'one' stores ways from [n-2]
16+
//'two' stores ways from [n-1]
1517
int climbStairs(int n) {
16-
if (n == 1) {
17-
return 1;
18+
int one = 1, two = 1;
19+
for(int i = 0; i < n - 1; ++i){
20+
int temp = one;
21+
one += two;
22+
two = temp;
1823
}
19-
if (n == 2) {
20-
return 2;
21-
}
22-
23-
int first = 1;
24-
int second = 2;
25-
26-
int result = 0;
27-
28-
for (int i = 2; i < n; i++) {
29-
result = first + second;
30-
first = second;
31-
second = result;
32-
}
33-
34-
return result;
24+
return one;
3525
}
3626
};

0 commit comments

Comments
 (0)