题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
递归法:优点:代码简单,便于阅读,缺点:时间复杂度为O(N2),空间复杂度为O(N2)
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);
}
}
}
迭代法:时间复杂度为O(2N),空间复杂度为O(2)
public class Solution {
public int Fibonacci(int n) {
if(n==0)
return 0;
else if(n==1)
return 1;
else{
int x=0;
int y=1;
for(int i=2;i<=n;i++)
{
y=x+y;
x=y-x;
}
return y;
}
}
}