来源于《剑指offer》
package algorithm;
/*
* @author weijie
* 实现了递归求解斐波那契数列
* 实现了树形拆分后的自下往上计算求解斐波那契数列
* 矩阵公式比较生僻,暂未实现(2018-11-07)
* @date 2018-11-07
*/
public class Fibonacci {
public static void main(String[] args)
{
int n =40;
long start1 = System.currentTimeMillis();
System.out.println(fibonacciFromBottom(n));
long end1 = System.currentTimeMillis();
System.out.println("start:" +start1 +",end:" +end1 +",takes:"+(end1-start1));
long start2 = System.currentTimeMillis();
System.out.println(fibonacciByRecursion(n));
long end2 = System.currentTimeMillis();
System.out.println("start:" +start2 +",end:" +end2 +",takes:"+(end2-start2));
}
public static long fibonacciByRecursion(int n)
{
long result =0l;
long[] fi = {0,1};
if(n<2) return fi[n];
return fibonacciByRecursion(n-1)+fibonacciByRecursion(n-2);
}
public static long fibonacciFromBottom(int n)
{
long[] fi = {0,1};
if(n<2) return fi[n];
long fibonacciMinusTwo =0l;
long fibonacciMinusOne =1l;
long fibonacci =1l;
for(int i=1;i<n;i++)
{
fibonacci = fibonacciMinusOne + fibonacciMinusTwo;
fibonacciMinusTwo = fibonacciMinusOne;
fibonacciMinusOne = fibonacci;
}
return fibonacci;
}
}
经测试发现,在求f(40)的时候递归方式和自底向上的方式的效率就有了显著的差异,如下是实测截图
f(30)的测试结果
f(40)的测试结果