题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
1、最常见的递归算法,复杂度太高O(k^n)
//递归 --会做大量冗余计算
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-1);
}
}
};
2、利用数组存放之前的计算结果,时间负责度为O(n),空间复杂度也为O(n)
//数组存放--浪费空间
class Solution {
public:
int Fibonacci(int n) {
if(n<2){
return n;
}else{
int* a=new int[n+1]; //分配并初始化一个对象数组,注意生成动态数组的方法
int i;
a[0]=0;
a[1]=1;
for(i=2;i<=n;i++){
a[i]=a[i-1]+a[i-2];
}
return a[n];
}
}
};
3、动态规划。其实就是说,对于这个斐波那契数列来讲,只需要考虑当前值和之前的2个值即可。每次循环都可以进行一次状态转移。时间复杂度为O(n),空间复杂度为O(k)
//动态规划--状态转移
//只关心所求值与所求相邻的两个数
class Solution {
public:
int Fibonacci(int n) {
int last=0, recent=1; //前两个数
int now=n;
while(n>=2){
now=last+recent; //计算当前值
last=recent; //实现数据转移
recent=now;
n--;
}
return now;
}
};
//动态规划简化版
class Solution {
public:
int Fibonacci(int n) {
int last=0, recent=1; //前两个数
while(n-->0){
recent+=last
last=recent-last;
}
return last;
}
};
4、使用矩阵,复杂度会降到O(logn)
/* O(logN)解法:由f(n) = f(n-1) + f(n-2),可以知道
* [f(n),f(n-1)] = [f(n-1),f(n-2)] * {[1,1],[1,0]}
* 所以最后化简为:[f(n),f(n-1)] = [1,1] * {[1,1],[1,0]}^(n-2)
* 所以这里的核心是:
* 1.矩阵的乘法
* 2.矩阵快速幂(因为如果不用快速幂的算法,时间复杂度也只能达到O(N))
*/
public static int Fibonacci4(int n){
if (n < 1)
{
return 0;
}
if (n == 1 || n == 2)
{
return 1;
}
int[][] base = {{1,1},
{1,0}};
//求底为base矩阵的n-2次幂
int[][] res = matrixPower(base, n - 2);
//根据[f(n),f(n-1)] = [1,1] * {[1,1],[1,0]}^(n-2),f(n)就是
//1*res[0][0] + 1*res[1][0]
return res[0][0] + res[1][0];
}
//矩阵乘法
public static int[][] multiMatrix(int[][] m1,int[][] m2) {
//参数判断什么的就不给了,如果矩阵是n*m和m*p,那结果是n*p
int[][] res = new int[m1.length][m2[0].length];
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m2[0].length; j++) {
for (int k = 0; k < m2.length; k++) {
res[i][j] += m1[i][k] * m2[k][j];
}
}
}
return res;
}
/*
* 矩阵的快速幂:
* 1.假如不是矩阵,叫你求m^n,如何做到O(logn)?答案就是整数的快速幂:
* 假如不会溢出,如10^75,把75用用二进制表示:1001011,那么对应的就是:
* 10^75 = 10^64*10^8*10^2*10
* 2.把整数换成矩阵,是一样的
*/
public static int[][] matrixPower(int[][] m, int p) {
int[][] res = new int[m.length][m[0].length];
//先把res设为单位矩阵
for (int i = 0; i < res.length; i++) {
res[i][i] = 1;
} //单位矩阵乘任意矩阵都为原来的矩阵
//用来保存每次的平方
int[][] tmp = m;
//p每循环一次右移一位
for ( ; p != 0; p >>= 1) {
//如果该位不为零,应该乘
if ((p&1) != 0) {
res = multiMatrix(res, tmp);
}
//每次保存一下平方的结果
tmp = multiMatrix(tmp, tmp);
}
return res;
}
5、利用生成函数,时间复杂度会变成O(1)
public static int Fibonacci(int n){
double root=Math.sqrt(5);
return (int)Math.round(Math.pow(((1 + root)/2), n) / root - Math.pow(((1 - root)/2), n) / root);
}
之所以用Math.round(),是因为double都会有那么一丁点的误差,所以需要使用四舍五入来补上这点残差。它其实是递推公式的解:
转自博客:https://blog.youkuaiyun.com/qq_35082030/article/details/65450721