forked from shogunsea/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclimbing-stairs.java
59 lines (48 loc) · 1.19 KB
/
climbing-stairs.java
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
48
49
50
51
52
53
54
55
56
57
58
59
public class Solution {
/**
* @param n: An integer
* @return: An integer
*/
public int climbStairs(int n) {
// write your code here
if (n <= 1) {
return 1;
}
// define state: dp[i] ways to get to stair i.
int[] dp = new int[n + 1];
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
// naive recursion will TLE.
// public int climbStairs(int n) {
// // write your code here
// if (n == 1) {
// return 1;
// } else if (n == 2) {
// return 2;
// }
// return climbStairs(n - 1) + climbStairs(n - 2);
// }
}
public class Solution {
public int climbStairs(int n) {
if (n <= 2) {
return n;
}
int first = 1;
int second = 2;
int res = 0;
int stairs = n - 2;
while (stairs > 0) {
res = first + second;
first = second;
second = res;
stairs--;
}
return res;
}
}