题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
解题思路:使用递归的思想即可,缺点是比较耗时。
public class Solution {
public int Fibonacci(int n) {
return Febo(n);
}
static int Febo(int n){
if(n <3 ){
if(n==2)
return 1;
return n;
}
return Febo(n-1)+Febo(n-2);
}
}
第二种解法:利用循环的方法,时间复杂度较低:
public class Solution {
public int Fibonacci(int n) {
if(n<3){
if(n == 2){
return 1;
}
return n;
}
int one_number = 0;
int two_number = 1;
int result = 0;
for(int i =2;i<=n;i++){
result = one_number + two_number;
one_number = two_number;
two_number = result;
}
return result;
}
}