zoukankan      html  css  js  c++  java
  • 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)))

  • 相关阅读:
    Table XXX is marked as crashed and should be repaired问题
    冗余带来的麻烦
    thinkPHP模板引擎案例
    css案例学习之float浮动
    css案例学习之父子块的margin
    block,inline和inline-block概念和区别
    css案例学习之div与span的区别
    css案例学习之盒子模型
    css案例学习之层叠样式
    css案例学习之继承关系
  • 原文地址:https://www.cnblogs.com/songya/p/10262435.html
Copyright © 2011-2022 走看看