File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ public record ClimbingStairsBottomUpOptimized () {
2
+ public int climbingStairsBottomUpOptimized (int n ) {
3
+ if (n <= 2 ) {
4
+ return n ;
5
+ }
6
+ // Set 'oneStepBefore' and 'twoStepsBefore' as the base cases.
7
+ int oneStepBefore = 2 ;
8
+ int twoStepsBefore = 1 ;
9
+ for (int i = 3 ; i < n + 1 ; i ++) {
10
+ // Calculate the number of ways to reach the current step.
11
+ int current = oneStepBefore + twoStepsBefore ;
12
+ // Update the values for the next iteration.
13
+ twoStepsBefore = oneStepBefore ;
14
+ oneStepBefore = current ;
15
+ }
16
+ return oneStepBefore ;
17
+ }
18
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .HashMap ;
2
+ import java .util .Map ;
3
+
4
+ public class ClimbingStairsTopDown {
5
+ Map <Integer , Integer > memo = new HashMap <>();
6
+
7
+ public int climbingStairsTopDown (int n ) {
8
+ // Base cases: With a 1-step staircase, there's only one way to
9
+ // climb it. With a 2-step staircase, there are two ways to climb it.
10
+ if (n <= 2 ) {
11
+ return n ;
12
+ }
13
+ if (memo .containsKey (n )) {
14
+ return memo .get (n );
15
+ }
16
+ // The number of ways to climb to the n-th step is equal to the sum
17
+ // of the number of ways to climb to step n - 1 and to n - 2.
18
+ memo .put (n , climbingStairsTopDown (n - 1 ) + climbingStairsTopDown (n - 2 ));
19
+ return memo .get (n );
20
+ }
21
+ }
You can’t perform that action at this time.
0 commit comments