递归的优化策略

目录

目标

实战(以斐波那契数列为例)

什么是斐波那契数列

实现


目标

  • 熟悉递归的几种优化策略(转化为非递归方法、保存已经存在的值的方法、尾递归方法)。

实战(以斐波那契数列为例)

什么是斐波那契数列

指的是这样一个数列:0、1、1、2、3、5、8、13、21、34……即当前项=左边相邻的两项之和。表达式为:F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)(≥ 2,∈ N*)


实现

package com.ctx;

/**
 *
 * @describe 斐波那契数列:0、1、1、2、3、5、8、13、21、34
 */
public class A {
    static int[] data;

    public static void main(String[] args) {
        long a=System.currentTimeMillis();
        System.out.println("普通方法:"+A.fun(40));
        System.out.println("普通方法用时:"+(System.currentTimeMillis()-a));

        a=System.currentTimeMillis();
        System.out.println("优化方法一(非递归):"+A.fun2(40));
        System.out.println("优化方法一(非递归):"+(System.currentTimeMillis()-a));

        a=System.currentTimeMillis();
        System.out.println("优化方法二(保存递归值):"+A.fun3(40));
        System.out.println("优化方法二(保存递归值):"+(System.currentTimeMillis()-a));

        a=System.currentTimeMillis();
        System.out.println("优化方法三(尾递归):"+A.fun4(0,1,40));
        System.out.println("优化方法三(尾递归):"+(System.currentTimeMillis()-a));
    }

    /**
     * 普通方法:根据表达式计算当前项。
     * @param n
     * @return
     */
    public static int fun(int n){
        if(n==1){
            return 0;
        }else if(n==2){
            return 1;
        }
        return fun(n-1)+fun(n-2);
    }

    /**
     * 优化方法一:非递归
     * @param n
     * @return
     */
    public static int fun2(int n){
        if(n==1){
            return 0;
        }else if(n<4){
            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 n
     */
    public static int fun3(int n){
        if(n==1){
            return 0;
        }else if(n==2){
            return 1;
        }
        if(data==null){
            data = new int[n+1];
        }
        if(data[n]>0){
            return data[n];
        }else{
            data[n]=fun3(n-1)+fun3(n-2);
        }
        return data[n];
    }

    /**
     * 尾部递归
     * 尾递归的核心思想是:避免函数之间的加减乘除操作,优化栈内存释放,即最后的return接的是一个函数而不是多个函数之间的操作。
     * 时间复杂度:O(n)
     * @param pre 上上一次运算出来的结果
     * @param res 上一次运算出来结果
     * @param n 当前项数
     * @return
     */
    public static int fun4(int pre,int res,int n) {
        if(n==1){
            return 0;
        }else if (n < 3){
            return res;
        }
        return fun4(res, pre + res, n -1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值