斐波那契數(shù)列遞歸與非遞歸實現(xiàn)

我們知道斐波那契數(shù)列的實現(xiàn)方式是,下標(biāo)為1或者2時,其值就是1,當(dāng)下標(biāo)大于3時,則f(n) = f(n-1) + f(n-2);下面編寫了遞歸與非遞歸兩種實現(xiàn)方式(Java代碼):

public class Fibonacci {
    public static void main(String []args) {
        System.out.println(FibonacciLoop(40));
        System.out.println(FibonacciNoLoop(40));
    }

    public static long FibonacciLoop(int index) {
        if (index <= 0) {
            System.out.println("Parameter Error!");
            return -1;
        }
        if (index == 1 || index == 2) {
            return 1;
        }
        else {
            return FibonacciLoop(index - 1) + FibonacciLoop(index - 2);
        }
    }

    public static long FibonacciNoLoop(int index) {
        if (index <= 0) {
            System.out.println("Parameter Error!");
            return -1;
        }       
        if (index == 1 || index == 2) {
            return 1;
        }

        long m = 1L;
        long n = 1L;
        long result = 0;

        for (int i = 3; i <= index; i++) {
            result = m + n;
            m = n;
            n = result;
        }

        return result;
    }
}

測試當(dāng)下標(biāo)為40時,結(jié)果為102334155。

斐波那契數(shù)列還有很多衍生的問題,比如青蛙跳臺階問題:

 一只青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法。

可以把n級臺階時的跳法看成是n的函數(shù),記為f(n)。
當(dāng)n>2時,第一次跳的時候就有兩種不同的選擇:
一是第一次只跳1級,此時跳法數(shù)目等于后面剩下的n-1級臺階的跳法數(shù)目,即為f(n-1);
另一種選擇是第一次跳2級,此時跳法數(shù)目等于后面剩下n-2級臺階的跳法數(shù)目,即為f(n-2)。
因此,n級臺階的不同跳法的總數(shù)f(n)=f(n-1)+f(n-2)。
遞歸與非遞歸的Java代碼。

public static long FrogJumpLoop(int n) {
        if (n <= 0) {
            System.out.println("Parameter Error!");
            return -1;
        }
        if (n == 1) {
            return 1;
        }
        if (n == 2) {
            return 2;
        }
        else {
            return FrogJumpLoop(n - 1) + FrogJumpLoop(n - 2);
        }
    }

    public static long FrogJumpNoLoop(int n) {
        if (n <= 0) {
            System.out.println("Parameter Error!");
            return -1;
        }
        if (n == 1) {
            return 1;
        }
        if (n == 2) {
            return 2;
        }

        long step1 = 1L;
        long step2 = 2L;
        long result = 0;

        for (int i = 3; i <= n; i++) {
            result = step1 + step2;
            step1 = step2;
            step2 = result;
        }

        return result;
    }

其他關(guān)于斐波那契變形的題目可以參考博客:http://blog.csdn.net/u010177286/article/details/47129019

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容