码迷,mamicode.com
首页 > 编程语言 > 详细

斐波那契问题(java)

时间:2017-02-19 21:11:45      阅读:166      评论:0      收藏:0      [点我收藏+]

标签: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)

标签:turn   pre   矩阵相乘   public   ase   bsp   []   nbsp   base   

原文地址:http://www.cnblogs.com/b-dong/p/6417075.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!