[LeetCode] 70. Climbing Stairs

You are climbing a staircase. 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.

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

Constraints:
1 <= n <= 45

爬楼梯。

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/climbing-stairs 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题有两种解法,一种是数学解法,一种是动态规划。

思路一 - 数学解法

首先是数学解法,这个题本质上是斐波那契数列。当输入为1, 2, 3, 4, 5, 6, 7, 8, 9, 10时,观察输出为1, 2, 3, 5, 8, 13, 21, 34, 55, 89。所以做法就很直观了。

复杂度

时间O(n)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int climbStairs(int n) {
// corner case
if (n <= 1) {
return n;
}

// normal case
int zero = 1;
int first = 1;
int cur = 0;
for (int i = 2; i <= n; i++) {
cur = zero + first;
zero = first;
first = cur;
}
return cur;
}
}

思路二 - 动态规划

dp[i] 数组的定义是跑到第 i 层楼的时候,上楼梯的组合数是多少。几个初始值是 dp[0] = 0, dp[1] = 1, dp[2] = 2。因为每次既可以爬一层楼,也可以爬两层楼,所以当你需要知道第i层楼的爬法的时候,你需要看的是我爬到 i - 2 层楼有几种爬法和我爬到 i - 1 层楼有几种爬法。所以状态转移方程就是 dp[i] = dp[i - 1] + dp[i - 2]。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int climbStairs(int n) {
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}

javascript实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function (n) {
if (n === 0) return 0;
let dp = [n + 1];
dp[0] = 1;
dp[1] = 1;
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
};

相关题目

1
2
3
4
70. Climbing Stairs
509. Fibonacci Number
746. Min Cost Climbing Stairs
1137. N-th Tribonacci Number

[LeetCode] 70. Climbing Stairs
https://shurui91.github.io/posts/2952065353.html
Author
Aaron Liu
Posted on
February 13, 2020
Licensed under