forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path70-Climbing-Stairs.cpp
More file actions
36 lines (29 loc) · 810 Bytes
/
70-Climbing-Stairs.cpp
File metadata and controls
36 lines (29 loc) · 810 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
Climbing stairs, either 1 or 2 steps, distinct ways to reach top
Ex. n = 2 -> 2 (1 + 1, 2), n = 3 -> 3 (1 + 1 + 1, 1 + 2, 2 + 1)
Recursion w/ memoization -> DP, why DP? Optimal substructure
Recurrence relation: dp[i] = dp[i - 1] + dp[i - 2]
Reach ith step in 2 ways: 1) 1 step from i-1, 2) 2 steps from i-2
Time: O(n)
Space: O(1)
*/
class Solution {
public:
int climbStairs(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
int first = 1;
int second = 2;
int result = 0;
for (int i = 2; i < n; i++) {
result = first + second;
first = second;
second = result;
}
return result;
}
};