遞歸的優化


遞歸的優化主要有三個方法:

1.循環代替遞歸

2.緩存中間結果優化遞歸

3.尾遞歸

我們通過斐波拉契數列來展示性能的優化效果

首先看下普通遞歸的效果

接着我們使用循環來替代遞歸

緩存中間結果優化遞歸

最后,測測尾遞歸

 

附上代碼

/**
 * 斐波那契數列
 */
public class Fiber {
    public  static int fun(int n){
        // 遞歸結束條件
        if(n<=1) return n;
        //等價關系式  實現功能
        return fun(n-1)+fun(n-2);
    }


    public static int fun1(int n){
        if(n==1 || n==2){
            return 1;
        }
        int f1 = 1;
        int f2 = 1;
        int f3 = f1+f2;
        while(n>3){
            f1=f2;
            f2=f3;
            f3 =f1+f2;
            n--;
        }
        return f3;
    }
    public static int[] dataCache = new int[46];
    public static int fun2(int n){
        if(n<=1) {
            return n;
        }
        if(dataCache[n]!=0){
            return dataCache[n];
        }
        int res = fun2(n-1)+fun2(n-2);
        dataCache[n]=res;
        return res;
    }

    public static int fun3(int n,int pre,int res){
        if(n<=1){
            return res;
        }
        return fun3(n-1,res,pre+res);
    }

    public static void main(String[] args) {

        Long start =  System.currentTimeMillis();
        System.out.println(fun3(45,0,1));
        Long end = System.currentTimeMillis();
        //1134903170
        System.out.println("尾遞歸優化遞歸算斐波拉契數列耗時:"+(end -  start)+"ms");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM