斐波那契數列的兩種實現(遞歸和非遞歸)


查找斐波納契數列中第 N 個數。

所謂的斐波納契數列是指:

  • 前2個數是 0 和 1 。
  • i 個數是第 i-1 個數和第i-2 個數的和。

斐波納契數列的前10個數字是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

像這樣的題,看到肯定想到遞歸算法來做,這是一種很重要的思想(雖然遞歸實現效率低,但是簡潔的代碼就能達到該有的功能),

下面上源碼。

遞歸算法:

public int fibonacci(int n) {
        // write your code here
        if(n == 1)
            return 0;
        else if(n == 2)
            return 1;
        return  fibonacci(n-2)+fibonacci(n-1);
    }

非遞歸:

public int fibonacci(int n) {
        // write your code here
        int a = 0;
        int b = 1;
        int result = 0;
        if(n == 1)
            return 0;
        else if(n == 2)
            return 1;
        for(int i = 3;i<n+1;i++){
            result = a +b;
            a = b;
            b = result;
        }
        return result;
    }

 


免責聲明!

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



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