-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclimbing-stairs.cpp
47 lines (40 loc) · 915 Bytes
/
climbing-stairs.cpp
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
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
unordered_map<int, int> bag;
int climbStairs(int n) {
if ( n < 0 ) { return 0; }
if ( n == 0 ) {
return 1;
}
if ( bag.count(n) ) {
return bag[n];
}
bag[n] = climbStairs(n-1) + climbStairs(n-2);
return bag[n];
}
};
//--- method 1: dp iteration
class Solution {
public:
int climbStairs(int n) {
vector<int> dp(n+1, 0);
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[i] = dp[i-1]+dp[i-2];
}
return dp.back();
}
};
//--- method 2: O(1) space
class Solution {
public:
int climbStairs(int n) {
int last1 = 1, last2 = 1;
for (int i = 2; i <= n; ++i) {
auto tmp = last1+last2;
last2 = last1;
last1 = tmp;
}
return last1;
}
};