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

爬楼梯 #6

Open
louzhedong opened this issue Apr 24, 2018 · 0 comments
Open

爬楼梯 #6

louzhedong opened this issue Apr 24, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

题目:爬楼梯

出处:LeetCode 算法第70题

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

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

**注意:**给定 n 是一个正整数。

示例 1:

输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1.  1 步 + 1 步
2.  2 步

示例 2:

输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1.  1 步 + 1 步 + 1 步
2.  1 步 + 2 步
3.  2 步 + 1 步

分析

本题思路为动态规划,考虑最后一步的走法,有两种情况,走一步或者走两步,所以f(n) = f(n-1) + f(n-2)

解答

方法一:不创建额外空间

var climbStairs = function (n) {
  if (n === 1) {
    return 1;
  } else if (n === 2) {
    return 2;
  } else {
    return climbStairs(n - 1) + climbStairs(n - 2);
  }
};

类似于Fibonacci数列,由于在内部做了大量重复的运算,有很差的时间复杂度

解法二:创建一个额外的数组

var climbStairs = function (n) {
  var dp = [];
  dp[1] = 1;
  dp[2] = 2;
  if (n >= 3) {
    for (i = 3; i <= n; i++) {
      dp[i] = dp[i - 1] + dp[i - 2];
    }
  }
  return dp[n];
}

时间复杂度为O(n),但需要创建一个额外的数组空间。

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

No branches or pull requests

1 participant