70. Climbing Stairs

题目描述:

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

例1

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

例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

解:用Dynamic Programming(动态规划)

思路:这个问题可以分解为子问题,并且它包含最优的子结构属性,即它的最优解可以从其子问题的最优解中构建,可以使用动态规划来解决这个问题。

到达第 i 步有两种方式:

1、从第 (i - 1)步中,爬一步到达;

2、从第(i - 2)步中,爬两步到达。

所以:到达第 i 步 = 到达第(i - 1)步 + 到达第(i-2)步
dp[i] = dp[i-1] + dp[i-2]

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

复杂度分析:

时间复杂度:O(n)

空间复杂度:O(n)

(leetcode solution链接:https://leetcode.com/articles/climbing-stairs/)

  (Top Down & Bottom Up链接:https://leetcode.com/problems/climbing-stairs/discuss/207575/Javascript-Top-Down-and-Bottom-Up-5-different-solutions-(3-faster-than-100-O(n)))

posted @ 2019-01-13 13:54  侧耳倾听5  阅读(123)  评论(0编辑  收藏  举报