LeetCode 070. 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.
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
中文
假设你正在爬楼梯。需要 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 步
解法一
思路
这题是斐波拉契数列的一个经典实例。
这题不妨倒着想,对于第n
级台阶,有多少种不同的方法爬到这一级呢?想想爬到第n
级台阶的前一次在哪级台阶上,题目说爬一次可以爬1或2个台阶,那么第n
级台阶的前一次就是第n-1
级和第n-2
级台阶了,而且有且仅有这两种情况。形式化来说,令爬到第n
级台阶的方法数为f(n)
,那么f(n) = f(n - 1) + f(n - 2)
,看到这个公式,是不是就是著名的斐波拉契数列公式了呢?结合题目实际,我们确定一下初始值:f(1) = 1
和f(2) = 2
。
我们采用自底向上的求解思想来实现这个斐波拉契数列的计算。
Python
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 2:
return n
a = 1
b = 2
for i in range(3, n + 1):
c = b
b += a
a = c
return b
Java
public class Solution {
public int climbStairs(int n) {
if (n <= 2) {
return n;
}
int a = 1;
int b = 2;
for (int i = 3; i <= n; i++) {
int c = b;
b += a;
a = c;
}
return b;
}
}
C++
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
int a = 1;
int b = 2;
for (int i = 3; i <= n; i++) {
int c = b;
b += a;
a = c;
}
return b;
}
};
最近也在刷力扣,来看看