File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments