题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
斐波那契数列: 1,1,2,3,5,8,13,21,34.........
解题思路:斐波那契数列为第三项起该项为前两项之和(此处需注意有第0项)
参考答案:
class Solution {
public:
int Fibonacci(int n) {
if(n==0)
{
return 0;
}
if(n > 39)
{
return 0;
}
if(n == -1)
{
return -1;
}
if(n == 1 || n == 2)
{
return 1;
}
return (Fibonacci(n-1) + Fibonacci(n-2));
}
};
优化代码:
//当递归太多次之后,很费时间(有很多重复的调用),可以考虑非递归版
class Solution {
public:
int Fibonacci(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n > 39)
return 0;
int last_val = 0;
int current_val = 1;
int res = 1;
n--;
while (n--)
{
res = last_val + current_val;
last_val = current_val;
current_val = res;
}
return res;
}
};