-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClimbingStairs.java
53 lines (45 loc) · 1.27 KB
/
ClimbingStairs.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
package solutions;
// [Problem] https://leetcode.com/problems/climbing-stairs
class ClimbingStairs {
// Recursion with memoization
// O(n) time, O(n) space
private int[] memo;
public int climbStairs(int n) {
if (n <= 1) {
return n;
}
memo = new int[n + 1];
memo[1] = 1;
memo[2] = 2;
return climbStairsRecursion(n);
}
private int climbStairsRecursion(int n) {
if (memo[n] > 0) {
return memo[n];
}
memo[n] = climbStairsRecursion(n - 1) + climbStairsRecursion(n - 2);
return memo[n];
}
// Bottom up with memoization
// O(n) time, O(n) space
public int climbStairsBottomUp(int n) {
if (n <= 1) {
return n;
}
memo = new int[n + 1];
memo[1] = 1;
memo[2] = 2;
for (int i = 3; i <= n; i++) {
memo[i] = memo[i - 2] + memo[i - 1];
}
return memo[n];
}
// Test
public static void main(String[] args) {
ClimbingStairs solution = new ClimbingStairs();
int input = 3;
int expectedOutput = 3;
int actualOutput = solution.climbStairs(input);
System.out.println("Test passed? " + (expectedOutput == actualOutput));
}
}