假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
- 1 阶 + 1 阶
- 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
- 1 阶 + 1 阶 + 1 阶
- 1 阶 + 2 阶
- 2 阶 + 1 阶
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/climbing-stairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路概述:
如果一共有n个台阶,那,最后的台阶走完方法可以是走一节或者走两节。那走法就变成了f(n-1)+f(n-2),由此可以看出,这是个斐波那契数列。
递归解法,超时:
class Solution {
public int climbStairs(int n) {
return cb(n);
}
private int cb(int x) {
if(x==1) return 1;
if(x==2) return 2;
else return cb(x-1)+cb(x-2);
}
}
动态规划:
class Solution {
public int climbStairs(int n) {
if(n <= 2){
return n;
}
int cur = 1;
int next = 2;
while(n-2 >0){
next = cur + next;
cur = next - cur;
n--;
}
return next;
}
}