Skip to content

Commit 71d4c5c

Browse files
authored
Merge pull request neetcode-gh#1242 from aniruddhakj/patch-1
Updating 70.climbing_stairs.cpp
2 parents 3d16d54 + cabffc3 commit 71d4c5c

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

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

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,31 @@
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
99
Time: O(n)
1010
Space: O(1)
1111
*/
1212

13-
class Solution {
13+
class SolutionBottomUp {
14+
public:
15+
//Fibonacci series : 'one' stores ways from [n-2]
16+
//'two' stores ways from [n-1]
17+
int climbStairs(int n) {
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;
23+
}
24+
return one;
25+
}
26+
};
27+
28+
29+
class SolutionTopDown {
1430
public:
1531
int climbStairs(int n) {
1632
if (n == 1) {

0 commit comments

Comments
 (0)