Leetcode problem 10 - Climbing Stairs
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps Example 2:
Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function (n) {
if (n === 1) return 1;
const steps = new Array(n + 1);
steps[0] = 0;
steps[1] = 1;
steps[2] = 2;
for (let i = 3; i <= n; i++) {
steps[i] = steps[i - 1] + steps[i - 2];
}
return steps[n];
};
In this implementation, the function climbStairs
uses an array steps
to store the number of ways to climb to each step. The number of ways for each step is calculated by summing the number of ways to the previous two steps, similar to the Fibonacci sequence. The result is then returned for the n
th step, representing the number of distinct ways to reach the top of the staircase with n
steps.
Leave a comment