题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=100000
解:
都知道这个东西其实就是f(n) = f(n-1) + f(n-2)。这一题的第一个解法递归法就是直接代入即可。
-
解法1递归法:
public class Solution { public int Fibonacci(int n) { if(n <= 1) return n; return Fibonacci(n-1) + Fibonacci(n-2); } }
递归的缺点就是非常的吃内存,一旦题目的深度过大,就会因为同时开太多的内存out of memory。
比如说f(4)
= f(3) + f(2)
= f(2) + f(1) + f(1) + f(0)
= f(1) + f(0) + f(1) + f(1) + f(0)。关是一个f(4)就同一时间开了五个方法,开了过多的方法就会占用太多的内存。
而且,关是f(1)的答案就记录了3次,在时间的消耗上也是非常的大,远超o(n)。
-
解法2迭代法:
public class Solution { public int Fibonacci(int n) { int[] array = new int[n+1]; array[0] = 0; array[1] = 1; for(int i=2; i<=n; i++){ array[i] = array[i-1] + array[i-2]; } return array[i]; } }
修复了递归的一系列问题,首先解决了非常吃内存的问题,只是开数组的话,比开一个方法所消耗的内存要少很多。
其次是加快了时间,到达了O(n)的复杂度。
但是还是很消耗内存空间,一旦传入的n太大,就要创建一个非常大的数组。
-
解法3迭代节约空间:
public class Solution { public int Fibonacci(int n) { if(n <= 1) return n; int tem1 = 0; int tem2 = 1; for(int i=2; i<=n; i++){ tem2 = tem2 + tem1; tem1 = tem2 - tem1; } return tem2; } }
由于数组中某一个数的值和且只和前面两个数相关,所以只要一直更新这两个数的值即可。
由f(n) = f(n-1) + f(n-2)可以推算出,f(n+1) = f(n+2) - f(n)
拿f(4)进行验算:
i=2,tem2 = 1+0=1,tem1 = 1-0=1;
//先将tem2更新到array[2],再将tem1更新到array[1](array[2]-array[0]得到)
i=3,tem2 = 1+1=2,tem1 = 2-1=1;
i=4,tem2 = 2+1=3,tem1 = 3-1=2;相比上一种方法节约了更多的空间,可以说是O(n)复杂度下的最优解了。
-
解法4尾递归:
尾递归同样避免了内存使用过多的问题,
public class Solution { public int Fibonacci(int n) { return } /** 计算第n位斐波那契数列的值 @param n 第n个数 @param acc1 第n个数 @param acc2 第n与第n+1个数的和 @return 返回斐波那契数列值 */ public int Fibonacci(int n, int acc1, int acc2){ if(n <= 1) return n; return Fibonacci(n-1, acc2, acc1 + acc2); } }
关于尾递归可以参考这篇:
浅谈尾递归 - 司马彰的学习专栏 - SegmentFault 思否
https://segmentfault.com/a/1190000018153141