斐波那契数列四种解法

该博客探讨了斐波那契数列的不同计算方法,包括递归、动态规划、循环处理和尾递归优化。通过比较它们的时间和空间复杂度,展示了如何从O(N^2)降低到O(n),并提供了具体的Java实现代码,以提高算法效率。
摘要由CSDN通过智能技术生成
/**
 * 斐波那契数列解法
 */
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));
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值