Skip to content

Commit 9d2397c

Browse files
authored
Merge pull request neetcode-gh#166 from r1cky0/patch-12
Create 70-Climbing-Stairs.java
2 parents a5a837c + 6803809 commit 9d2397c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

java/70-Climbing-Stairs.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
//optimal
2+
class Solution {
3+
public int climbStairs(int n) {
4+
int a = 1;
5+
int b = 1;
6+
int c;
7+
8+
for (int i = 0; i < n - 1; i++) {
9+
c = a + b;
10+
a = b;
11+
b = c;
12+
}
13+
return b;
14+
}
15+
}
16+
17+
//bottom up
18+
class Solution {
19+
public int climbStairs(int n) {
20+
int[] dp = new int[n + 1];
21+
dp[0] = 1;
22+
dp[1] = 1;
23+
24+
for (int i = 2; i < n + 1; i++) {
25+
dp[i] = dp[i - 1] + dp[i - 2];
26+
}
27+
return dp[n];
28+
}
29+
}
30+
31+
//top down with memo[]
32+
class Solution {
33+
public int climbStairs(int n) {
34+
int[] memo = new int[n + 1];
35+
Arrays.fill(memo, -1);
36+
37+
return climbStairs(n - 1, memo) + climbStairs(n - 2, memo);
38+
}
39+
40+
private int climbStairs(int n, int[] memo) {
41+
if (n < 0) return 0;
42+
if (n == 0 || n == 1) {
43+
memo[n] = 1;
44+
return memo[n];
45+
}
46+
if (memo[n] != -1) return memo[n];
47+
48+
memo[n] = climbStairs(n - 1, memo) + climbStairs(n - 2, memo);
49+
return memo[n];
50+
}
51+
}

0 commit comments

Comments
 (0)