假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
解法1:递归法 比较好理解,但是会超时的
class Solution {
public int climbStairs(int n) {
if(n==0){
return 0;
}
if(n==1){
return 1;
}
if (n==2){
return 2;
}
return climbStairs(n-1)+climbStairs(n-2);
}
}
解法2:还是递归,但是用一个map来保存之前计算的数据,不用重复计算。也会超时,哭了。
class Solution {
public int climbStairs(int n) {
Map<Integer,Integer> map=new HashMap<>();
if(n==0){
return 0;
}
if(n==1){
return 1;
}
if (n==2){
return 2;
}
if (null!=map.get(n)){
return map.get(n);
}else{
int res=climbStairs(n-1)+climbStairs(n-2);
map.put(n,res);
return res;
}
}
}
解法3:通过了,用循环,利用前两个值,不断迭代更新。
class Solution {
public int climbStairs(int n) {
Map<Integer,Integer> map=new HashMap<>();
if(n==0){
return 0;
}
if(n==1){
return 1;
}
if (n==2){
return 2;
}
int res=0;
int prepre=1;
int pre=2;
for(int i=3;i<=n;i++){
res=pre+prepre;
prepre=pre;
pre=res;
}
return res;
}
}