问:有n步台阶,一次只能上1步或2步,共有多少种走法
1、递归
public static int f(int n){
if(n<=0){
throw new RuntimeException("n应大于0");
}
if(n==1 || n==2 || n==3){
return n;
}
return f(n-2)+f(n-1);
}
-
执行效率相对较低,递归调用浪费空间,调用太深(即n值越大)容易造成堆栈溢出
-
递归就是在过程或函数里面调用自身
-
在使用递归时,必须有一个明确的递归结束条件,称为递归出口
2、循环迭代
public static int f2(int n){
if(n<=0){
throw new RuntimeException("n应大于0");
}
if(n==1 || n==2 || n==3){
return n;
}
int two = 2;//初始化为走2阶台接
int one = 3;//初始化为走3阶台接
int sum = 0;
for (int i = 4; i <= n; i++) {
sum = two + one;
two = one;
one = sum;
}
return sum;
}
- 效率快