大家都知道斐波那契数列,现在要求输入一个整数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));
}
}