时间限制:1秒
空间限制:32768K
热度指数:257104
算法知识视频讲解
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。
n<=39
传统递归解法:
class Solution {
public:
int Fibonacci(int n) {
if (n == 1)
return 1;
if (n == 2)
return 1;
else
{
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
};
但是!使用递归解法是超过内存限制的!
使用非递归解法:
class Solution {
public:
int Fibonacci(int n) {
int f=0;
int g=1;
while(n!=0)
{
g=g+f;
f=g-f;
n--;
}
return f;
}
};
使用循环的解法,使用f表示当前值,使用g表示当前值的后一个值,然后循环加法计算出最后的结果。