题目描述:
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
解题思路:
1.利用递归的思想即可,设置好第一个和第二个数字,其余的等于前两个元素相加,一直递归到最终的结果即可。
缺点:递归虽然写起来简洁,实际上计算效率特别底,可以通过递归树来进行理解。由于计算效率太低,最终测试不通过。
class Solution
{
public:
int Fibonacci(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
};
2.由于递归的低效,因此可以采用循环迭代来解决这个问题,具体代码如下:
class Solution
{
public:
int Fibonacci(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
if (n > 1)
{
int tmp = 0;
int first = 0;
int second = 1;
for (int i = 0; i < n - 1; i++)
{
tmp = second + first;
first = second;
second = tmp;
}
return second;
}
else return -1; //代表出错了
}
};