斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368……
特别指出:第0项是0,第1项是第一个1。
这个数列从第三项开始,每一项都等于前两项之和。
请
方法一、基础循环写法
package test;
/**
*
* @author laoshifu
* 2021年12月8日
*/
public class Action {
public static void main(String[] args) {
int zero=0;
int one=1;
int two=1;
//注:从1月份开始有数值,故而从1开始
for (int i = 1; i < 10; i++) {
two=zero+one;
zero=one;
one=two;
}
System.out.println(two);
}
}
方法二、递归写法
package test;
/**
*
* @author laoshifu
* 2021年12月8日
*/
public class Action {
public static void main(String[] args) {
System.out.println(dfs(10));
}
public static int dfs(int i){
if(i==0){
return 0;
}
if(i==1||i==2){
return 1;
}
return dfs(i-1)+dfs(i-2);
}
}
结果是一样的。
效率对比:测试数据【45】
循环消耗时间:
递归消耗时间:
很明显,这类操作不适合用递归操作。
希望能大家所帮助。