案例:
有n步台阶,一次只能上1步或2步,共有多少种走法?链接: 斐波那契数列.
有两种解决思路:
- 递归
public class Test02 {
public static void main(String[] args) {
System.out.println(f(4));
}
public static int f(int n){
if (n<1){
throw new IllegalArgumentException(n + "不能小于1");
}
if (n==1 || n==2){
return n;
}
return f(n-2)+f(n-1);
}
}
- 迭代
public class Test02 {
public static void main(String[] args) {
System.out.println(f(4));
}
public static int f(int n){
if (n<1){
throw new IllegalArgumentException(n + "不能小于1");
}
if (n==1 || n==2){
return n;
}
int one = 2;
int two = 1;
int sum = 0;
for (int i=3;i <= n;i++){
sum = one+two;
two = one;
one = sum;
}
return sum;
}
}
总结:
- 递归思路更好理解,但存在栈内存溢出的危险,占内存十分耗时
- 迭代思路不好理解,但性能优良,运行时间秒杀递归