一、题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
题目来源:斐波那契数列–nowcoder
二、题目解析
class Solution {
public:
int Fibonacci(int n) {
// 既然是求斐波那契数列,一般两种思路吧,递归和循环迭代
// 我们先考虑递归版本的
#if 0
if (n <= 0)
{
return 0;
}
if (n == 1 || n == 2)
{
return 1;
}
return Fibonacci(n-1) + Fibonacci(n-2);
#endif
// 循环迭代版本
if (n <= 0)
{
return 0;
}
if (n == 1 || n == 2)
{
return 1;
}
int first = 1;
int second = 1;
int third = 0;
for(int i = 2; i < n; ++i)
{
third = first + second;
first = second;
second = third;
}
return third;
}
};
如有问题欢迎评论区指出,谢谢大家:)