问题描述:
斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,
后面的每一项数字都是前面两项数字的和。也就是:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
给定 N,计算 F(N)。
示例 1:
输入:2
输出:1
解释:F(2) = F(1) + F(0) = 1 + 0 = 1.
示例 2:
输入:3
输出:2
解释:F(3) = F(2) + F(1) = 1 + 1 = 2.
示例 3:
输入:4
输出:3
解释:F(4) = F(3) + F(2) = 2 + 1 = 3.
提示:
0 ≤ N ≤ 30
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fibonacci-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果:
方法一的结果:
方法二的结果:
代码描述:
方法一
由于N的大小有限制,所以值的类型int就够用了。另外设计全局变量map,存储计算过的值,防止重复计算。
class Solution {
public:
map<int, int> m;
int fib(int N) {
if(m.count(N) > 0)
return m[N];
int result = 0;
if(N < 2) return N;
else
{
result = fib(N-1) + fib(N-2);
}
m.insert(make_pair(N, result));
return result;
}
};
方法二
1,1,2,3,5,8,。。。。可以发现,每一个值,都是前两个的和。 所以,就采用累加的方式,即可求得最后的兔子数目。并且计算效果,也比方法一更高效。
class Solution {
public:
int fib(int n) {
if(n == 0)
{
return 0;
}
else if(n < 3)
{
return 1;
}
int sum = 0;
int a = 1, b = 1;
int temp = 3;
while(n >= temp)
{
sum = (a + b);
a = b;
b = sum;
++temp;
}
return sum;
}
};