求斐波那契数列的第n项
写一个函数,输入n,求斐波那契数列的第n项。斐波那契数列的定义:
image.png
解题思路
-
递归方法
image.png - 循环方法
代码
- 递归
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);
}
}
};
- 循环方式
class Solution{
public:
long long Fibonacci(int n)
{
int result[2] = {0,1};
if(n < 2)
{
return result[n];
}
long long fibOne = 1;
long long fibTwo = 0;
long long fibN = 0;
for(unsigned int i = 2;i <= n;++i)
{
fibN = fibOne + fibTwo;
fibTwo = fibOne;
fibOne = fibN;
}
return fibN;
}
};
网友评论