没有输出的输入是不完整的

0%

剑指offer-斐波那契数列

本文为剑指 offer 系列第九篇。
主要知识点就是斐波那契数列,非常常见,非常经典。

题目描述

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。 n<=39

解题思路

思路1

直接通过斐波那契的概念来进行计算,递归调用。

思路2

我们知道递归调用的时候,很多部分都是重复计算的,所以我们可以建立一个数组进行保存。

思路3

仔细想想,每次计算的时候,对我们真正有用的数据其实只有两个,所以我们只要能够保存好两个必要的数据即可依次的计算后面的数据,直到算出我们想要的数据。

解题代码

思路1代码

1
2
3
4
5
6
7
8
class Solution {
public:
int Fibonacci(int n) {
//方法1: 递归
if(n == 0)return 0;
if(n == 1) return 1;
return Fibonacci(n-1)+Fibonacci(n-2);
};

思路2代码

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int Fibonacci(int n) {
// 方法2: 数据保存在一个数组中
vector<int> a={0,1};
for(int i = 2;i<=39;i++){
a.push_back(a[i-1]+a[i-2]);
}
return a[n];

}
};

时间复杂度为O(n),空间复杂度为O(n)

思路3代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int Fibonacci(int n) {
// 方法3. 通过2个常量来进行数据的保存。
int first = 0,second = 1;
if(n == 0) return first;
if(n == 1) return second;
for(int i = 1; i<n; i++){
int temp = first + second;
first = second;
second = temp;
}
return second;
}
};

时间复杂度为O(n),空间复杂度为O(1)

以上,本题结束!