File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ package easy ;
2+
3+ import java .util .Arrays ;
4+
5+ public class ClimbingStairs70 {
6+
7+ // this gives TLE for n >= 42
8+ public static int climbStairs (int n ) {
9+
10+ if (n == 0 )
11+ return 1 ;
12+
13+ if (n < 0 )
14+ return 0 ;
15+
16+ int oneStep = climbStairs (n - 1 );
17+ int twoStep = climbStairs (n - 2 );
18+
19+ int totalClimbPossible = oneStep + twoStep ;
20+
21+ return totalClimbPossible ;
22+ }
23+
24+ // optimal code
25+ public static int climbStairsDP (int n , int [] storage ) {
26+
27+ if (n == 0 )
28+ return 1 ;
29+
30+ if (n < 0 )
31+ return 0 ;
32+
33+ if (storage [n ] != -1 )
34+ return storage [n ];
35+
36+ int oneStep = climbStairsDP (n - 1 , storage );
37+ int twoStep = climbStairsDP (n - 2 , storage );
38+
39+ int totalClimbPossible = oneStep + twoStep ;
40+
41+ storage [n ] = totalClimbPossible ;
42+
43+ return totalClimbPossible ;
44+ }
45+
46+ public static void main (String [] args ) {
47+
48+ // using Recrusive approach only
49+ int n = 45 ;
50+
51+ // System.out.println(climbStairs(n));
52+
53+ // using DP
54+ int [] storage = new int [n + 1 ];
55+ Arrays .fill (storage , -1 );
56+ System .out .println (climbStairsDP (n , storage ));
57+ }
58+ }
You can’t perform that action at this time.
0 commit comments