There are n stairs, and a person standing at the bottom can climb either 1 stair, 2 stairs or 3 staris at a time, count the number of ways that a person can reach at the top.
Imagine you're climbing a staircase. You can choose to climb 1, 2, or 3 steps at a time. To find the total number of ways to climb the entire staircase, you can break it down:
If the staircase is small (1, 2, or 3 steps): You can directly count the possible ways.
If the staircase is larger:
This recursive approach efficiently calculates the total number of climbing possibilities.
def climb(n):
if n < 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
return climb(n - 1) + climb(n - 2) + climb(n - 3)
n = 5
print(climb(n))
function climb(n) {
if (n < 0) {
return 0;
}
if (n === 1) {
return 1;
}
if (n === 2) {
return 2;
}
if (n === 3) {
return 4;
}
return climb(n - 1) + climb(n - 2) + climb(n - 3);
}
const n = 5;
console.log(climb(n));