一、題目描述
大家都知道斐波那契數列,現在要求輸入一個整數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;
}
};
如有問題歡迎評論區指出,謝謝大家:)