斐波那契問題(java)

來源:互聯網
上載者:User

標籤:turn   pre   矩陣相乘   public   ase   bsp   []   nbsp   base   

F(n)=F(n-1)+F(n-2)

1.迭代實現,O(2的N次方)

 1 /** 2      * 斐波那契 迭代實現 3      * @param n 4      * @return 5      */ 6     public int Fabonacci_1(int n){ 7         if(n<0)return 0; 8         if(n==1||n==2) return 1; 9         return Fabonacci_1(n-1)+Fabonacci_1(n-2);10     }

 

2.遞迴實現,O(N)

 1 /** 2      * 斐波那契 遞迴實現 3      * @param n 4      * @return 5      */ 6     public int Fabonacci_2(int n){ 7         if(n<0)return 0; 8         if(n==1||n==2) return 1; 9         int res = 1,pre=1,temp=0;10         for(int i=3;i<=n;i++){11             temp = res;12             res = res+pre;13             pre = temp;14         }15         return res;16     }

3.使用二階矩陣實現,O(logN)

 1 /** 2      * 斐波那契 二階矩陣實現 3      * @param n 4      * @return 5      */ 6     public int Fabonacci_3(int n){ 7         if(n<0)return 0; 8         if(n==1||n==2) return 1; 9         int[][] base={{1,1},{1,0}};10         int[][] res = matrixPower(base, n-2);11         return res[0][0]+res[1][0];12     }13     14     //使用二階矩陣求 斐波那契15     16     public int[][] matrixPower(int[][] m,int p){17         int[][] res = new int[m.length][m[0].length];18         //設定res為單位矩陣19         for(int i=0;i<res.length;i++){20             res[i][i]=1;21         }22         23         int[][] temp = m;24         for(;p!=0;p>>=1){25             if((p&1)!=0){26                 muliMatrix(res, temp);27             }28             muliMatrix(temp, temp);29             30         }31         return res;32     }33     34     35     //2個矩陣相乘36     public int[][] muliMatrix(int[][] m1,int[][] m2){37         int[][] res = new int[m1.length][m2[0].length];38         for(int i=0;i<m1.length;i++){39             for(int j=0;j<m2[0].length;j++){40                 for(int k=0;k<m2.length;k++){41                     res[i][j] += m1[i][k]*m2[k][j];42                 }43             }44         }45         return res;46     }

 

斐波那契問題(java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.