Skip to content

Commit bedf3d7

Browse files
committed
Add Climbing Stairs
1 parent 3c4bb50 commit bedf3d7

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
fun climbingStairsBottmoUp(n: Int): Int {
2+
if (n <= 2) {
3+
return n
4+
}
5+
val dp = IntArray(n + 1)
6+
// Base cases.
7+
dp[1] = 1
8+
dp[2] = 2
9+
// Starting from step 3, calculate the number of ways to reach each
10+
// step until the n-th step.
11+
for (i in 3..n) {
12+
dp[i] = dp[i - 1] + dp[i - 2]
13+
}
14+
return dp[n]
15+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
fun climbingStairsBottomUpOptimized(n: Int): Int {
2+
if (n <= 2) {
3+
return n
4+
}
5+
// Set 'oneStepBefore' and 'twoStepsBefore' as the base cases.
6+
var oneStepBefore = 2
7+
var twoStepsBefore = 1
8+
for (i in 3..n) {
9+
// Calculate the number of ways to reach the current step.
10+
val current = oneStepBefore + twoStepsBefore
11+
// Update the values for the next iteration.
12+
twoStepsBefore = oneStepBefore
13+
oneStepBefore = current
14+
}
15+
return oneStepBefore
16+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
fun climbingStairsTopDown(n: Int): Int {
2+
val memo = hashMapOf<Int, Int>()
3+
return climbingStairsTopDown(n, memo)
4+
}
5+
6+
fun climbingStairsTopDown(n: Int, memo: HashMap<Int, Int>): Int {
7+
// Base cases: With a 1-step staircase, there's only one way to
8+
// climb it. With a 2-step staircase, there are two ways to climb it.
9+
if (n <= 2) {
10+
return n
11+
}
12+
if (memo[n] != 0) {
13+
return memo[n]!!
14+
}
15+
// The number of ways to climb to the n-th step is equal to the sum
16+
// of the number of ways to climb to step n - 1 and to n - 2.
17+
memo[n] = climbingStairsTopDown(n - 1, memo) + climbingStairsTopDown(n - 2, memo)
18+
return memo[n]!!
19+
}

0 commit comments

Comments
 (0)