爬楼梯
假设你正在爬楼梯,需要n步你才能到达顶部。但每次你只能爬一步或者两步,你能有多少种不同的方法爬到楼顶部?
比如n=3,1+1+1=1+2=2+1=3,共有3种不同的方法
返回 3
递归的办法:
public class Solution {
/**
* @param n: An integer
* @return: An integer
*/
public int climbStairs(int n) {
// write your code here
if(n==1||n==2){
return n;
}
else{
return climbStairs(n-1)+climbStairs(n-2);
}
}
}
结果:超时了。
另一种:
public class Solution {
/**
* @param n: An integer
* @return: An integer
*/
public int climbStairs(int n) {
// write your code here
if(n==0){
return 0;
}
int a=1;
int b=1;
int c=1;
for(int i=1;i<n;i++){
c=a+b;
a=b;
b=c;
}
return c;
}
}