-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0070-climbing-stairs.java
54 lines (44 loc) · 1.04 KB
/
0070-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
//optimal
class Solution {
public int climbStairs(int n) {
int a = 1;
int b = 1;
int c;
for (int i = 0; i < n - 1; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}
}
//bottom up
class Solution {
public int climbStairs(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i < n + 1; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}
//top down with memo[]
class Solution {
public int climbStairs(int n) {
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
return climbStairs(n - 1, memo) + climbStairs(n - 2, memo);
}
private int climbStairs(int n, int[] memo) {
if (n < 0) return 0;
if (n == 0 || n == 1) {
memo[n] = 1;
return memo[n];
}
if (memo[n] != -1) return memo[n];
memo[n] = climbStairs(n - 1, memo) + climbStairs(n - 2, memo);
return memo[n];
}
}