/**
* 斐波那契数列解法
*/
public class Fibonacci {
private static int[] store = new int[46];
/**
* 递归
* 时间复杂度 O(N^2)
* 空间复杂度 O(N^2)
* @param n
* @return
*/
public static int fab(int n) {
if (n <= 2) {
return 1;
}
return fab(n-1) + fab(n-2);
}
/**
* 使用数组存储结果,时间、空间复杂度O(n)
* @param n
* @return
*/
public static int fabStore(int n) {
if (n <= 2) {
return 1;
}
if (store[n] > 0){
return store[n];
}
store[n] = fabStore(n-1) + fabStore(n-2);
return store[n];
}
/**
* 循环处理,不用递归 O(n)
* @param n
* @return
*/
public static int fabValue(int n) {
if (n <= 2) return 1;
int a = 1;
int b = 1;
int c = 0;
for (int i =3;i <= n ;i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
/**
* 尾递归,倒着算
* @param pre 上次结果
* @param res 当前结果
* @param n
* @return
*/
public static int tailFab(int pre,int res,int n) {
if (n <= 2){
return res;
}
return tailFab(res,res+pre,n-1);
}
public static void main(String[] args) {
// for (int i = 0;i <= 45;i++) {
// Long start = System.currentTimeMillis();
// System.out.println("i: "+i+","+fab(i)+",spend time :"+(System.currentTimeMillis()-start));
// }
// for (int i = 0;i <= 45;i++) {
// Long start = System.currentTimeMillis();
// System.out.println("i: "+i+","+fabStore(i)+",spend time :"+(System.currentTimeMillis()-start));
// }
// for (int i = 0;i <= 45;i++) {
// Long start = System.currentTimeMillis();
// System.out.println("i: "+i+","+fabValue(i)+",spend time :"+(System.currentTimeMillis()-start));
// }
for (int i = 0;i <= 45;i++) {
Long start = System.currentTimeMillis();
System.out.println("i: "+i+","+tailFab(1,1,45)+",spend time :"+(System.currentTimeMillis()-start));
}
}
}
斐波那契数列四种解法
该博客探讨了斐波那契数列的不同计算方法,包括递归、动态规划、循环处理和尾递归优化。通过比较它们的时间和空间复杂度,展示了如何从O(N^2)降低到O(n),并提供了具体的Java实现代码,以提高算法效率。
摘要由CSDN通过智能技术生成