题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
斐波那契数列的递推表达式为: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
思路一: 递归。时间复杂度大,牛客网运行不通过。代码如下。
C++
class Solution {
public:
int Fibonacci(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
return Fibonacci(n-1) + Fibonacci(n-2);
}
};
**思路二:**非递归。
C++
class Solution {
public:
int Fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
vector<int>Fib{0, 1}; //初始边界值
int temp;
for (int i = 2; i <= n; i++)
{
temp = Fib[i - 1] + Fib[i - 2]; //斐波那契数列的递推表达式
Fib.push_back(temp);
}
return Fib[n];
}
};
Python
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
if n == 1:
return 1
if (n > 1):
temp = 0
first = 0
second = 1
for i in range(n - 1):
temp = first + second
first = second
second = temp
return second
return None