Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit71d4c5c

Browse files
authored
Merge pull requestneetcode-gh#1242 from aniruddhakj/patch-1
Updating 70.climbing_stairs.cpp
2 parents3d16d54 +cabffc3 commit71d4c5c

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-
classSolution {
13+
classSolutionBottomUp {
14+
public:
15+
//Fibonacci series : 'one' stores ways from [n-2]
16+
//'two' stores ways from [n-1]
17+
intclimbStairs(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+
classSolutionTopDown {
1430
public:
1531
intclimbStairs(int n) {
1632
if (n ==1) {

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp