要注意非遞迴的話就是那一個變數幫助儲存當前下一項的值,然後依次挪動兩個指標往下即可
注意如果n太大 會溢位
1 public static long fib(int n){
2 if(n <= 1)
3 return n;
4 else
5 return fib(n-1) + fib(n-2);
6 }
7
8 public static long fib2(int n){
9 if(n==0)
10 return 0;
11 if(n<=2)
12 return 1;
13 int n1 = 1, n2 = 1;
14 int sn = 0;
15 for(int i = 2; i< n; i++){
16 sn = n1 + n2;
17 n1 = n2;
18 n2 = sn;
19 }
20 return sn;
21 }
2 if(n <= 1)
3 return n;
4 else
5 return fib(n-1) + fib(n-2);
6 }
7
8 public static long fib2(int n){
9 if(n==0)
10 return 0;
11 if(n<=2)
12 return 1;
13 int n1 = 1, n2 = 1;
14 int sn = 0;
15 for(int i = 2; i< n; i++){
16 sn = n1 + n2;
17 n1 = n2;
18 n2 = sn;
19 }
20 return sn;
21 }