Skip to content

Commit e9a9366

Browse files
committed
add: ClimbingStairsTopDown and fix climbingStairsBottomUpOptimized function naming
1 parent 3a443a4 commit e9a9366

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
}

0 commit comments

Comments
 (0)