-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathClimbingStairs70.java
58 lines (38 loc) · 1007 Bytes
/
ClimbingStairs70.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
package easy;
import java.util.Arrays;
public class ClimbingStairs70 {
// this gives TLE for n >= 42
public static int climbStairs(int n) {
if (n == 0)
return 1;
if (n < 0)
return 0;
int oneStep = climbStairs(n - 1);
int twoStep = climbStairs(n - 2);
int totalClimbPossible = oneStep + twoStep;
return totalClimbPossible;
}
// optimal code
public static int climbStairsDP(int n, int[] storage) {
if (n == 0)
return 1;
if (n < 0)
return 0;
if (storage[n] != -1)
return storage[n];
int oneStep = climbStairsDP(n - 1, storage);
int twoStep = climbStairsDP(n - 2, storage);
int totalClimbPossible = oneStep + twoStep;
storage[n] = totalClimbPossible;
return totalClimbPossible;
}
public static void main(String[] args) {
// using Recrusive approach only
int n = 45;
// System.out.println(climbStairs(n));
// using DP
int[] storage = new int[n + 1];
Arrays.fill(storage, -1);
System.out.println(climbStairsDP(n, storage));
}
}