Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode | 70. 爬楼梯 #86

Open
aermin opened this issue Jun 25, 2020 · 0 comments
Open

LeetCode | 70. 爬楼梯 #86

aermin opened this issue Jun 25, 2020 · 0 comments

Comments

@aermin
Copy link
Owner

aermin commented Jun 25, 2020

题目

image

题解

动态规划

思路及代码

/**
 * @param {number} n
 * @return {number}
 */
/**
 * 如果最后一步如果是跨一个台阶,那方案数就是前一个台阶有的方案数f(x-1);
 * 如果最后一步如果是跨两个台阶,那方案数就是前两个台阶有的方案数f(x-2);
 * 两种情况加起来就是x级台阶的方案数。
 * 转移方程:f(x)=f(x−1)+f(x−2)
 * 可以用数组存下每级台阶的方案数,空间复杂度O(n), 用滚动数组思想,空间复杂度优化成O(1)
 */
var climbStairs = function(n) {
    // 用数组存下每级台阶的方案数,空间复杂度O(n)
    // const dp = [];
    // dp[1] = 1;
    // dp[2] = 2;
    // for(let i = 3; i <= n; i++) {
    //     dp[i] = dp[i - 1] + dp[i - 2];
    // }
    // return dp[n];

    // 用滚动数组思想,空间复杂度优化成O(1)
    let prePre = 0, pre = 0, cur = 1;
    for(let i = 0; i < n; i++) {
        prePre = pre;
        pre = cur;
        cur = prePre + pre;
    }
    return cur;
};

复杂度分析

时间复杂度:循环执行 n次,每次花费常数的时间代价,故渐进时间复杂度为 O(n)。
空间复杂度:这里只用了常数个变量作为辅助空间,故渐进空间复杂度为 O(1)。

图解

  • 用数组存下每级台阶的方案数,空间复杂度O(n)

Jun-25-2020 13-07-22

  • 用滚动数组思想,空间复杂度优化成O(1):

70_fig1

Refence

爬楼梯 作者:LeetCode-Solution
画解算法:70. 爬楼梯 作者:灵魂画手

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant