题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。
n<=39
思路
很基础的题目,有递归和非递归两种实现思路。
代码
递归算法
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 class Solution {
public int Fibonacci(int n) {
int temp = 1;
int result = 0;
int temp2 = 1;
if(n==0)
return 0;
if(n==1||n==2)
return 1;
for(int i = 3;i<=n;i++){
result = temp +temp2;
temp = temp2;
temp2 = result;
}
return result;
}
}