方法一:
递归
class Solution {
public int climbStairs(int n) {
if(n==1) {
return 1;
}else if(n==2) {
return 2;
}else {
return climbStairs(n-1)+climbStairs(n-2);
}
}
}
递归会超时,可以转换为数组来实现,如下
方法二:
class Solution {
public int climbStairs(int n) {
int[] count=new int[n+1];
count[0]=1;
count[1]=2;
for(int i=2;i<n;i++) {
count[i]=count[i-1]+count[i-2];
}
return count[n-1];
}
}
方法三:
更简单
class Solution {
public int climbStairs(int n) {
int p=0,q=0,r=1;
for(int i=1;i<=n;i++) {
p=q;
q=r;
r=p+q;
}
return r;
}
}