大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項。
斐波那契(qi)數列,又稱黃金分割數列;以兔子繁殖爲例子而引入,故又稱爲“兔子數列”,指的是這樣一個數列:0、1、1、2、3、5、8、13、21、34、……
在數學上,斐波納契數列以如下遞歸的方法定義:F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2,n∈N*)
即表示爲:前兩個數相加等於第三個數
代碼1:
使用遞歸方法:
public class Solution {
public int Fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.Fibonacci(9));
}
}
代碼2:
public class Solution1 {
public int Fibonacci(int n) {
int one = 0;
int two = 1;
if(n == 0){
return 0;
}
if(n == 1){
return 1;
}
int result = 0;
for(int i = 2;i <= n;i++){
result = one + two;
one = two;
two = result;
}
return result;
}
public static void main(String[] args) {
Solution1 s = new Solution1();
System.out.println(s.Fibonacci(9));
}
}