Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

70. Climbing Stairs #211

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

70. Climbing Stairs

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 12 个台阶。你有多少种不同的方法可以爬到楼顶呢?

Example 1

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Note

Tcdian commented 4 years ago

Solution

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    const dp = new Array(n + 1);
    for (let i = 0; i <= n; i++) {
        if (i < 2) {
            dp[i] = 1;
        } else {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
    }
    return dp[n];
};
function climbStairs(n: number): number {
    const dp: number[] = new Array(n + 1);
    for (let i = 0; i <= n; i++) {
        if (i < 2) {
            dp[i] = 1;
        } else {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
    }
    return dp[n];
}