大家都知道斐波那契数列,现在要求输入一个正整数 n ,请你输出斐波那契数列的第 n 项。
斐波那契数列是一个满足
的数列
数据范围:
要求:空间复杂度
,时间复杂度
,本题也有时间复杂度
的解法
一个正整数n
输出一个正整数。
4
3
根据斐波那契数列的定义可知,fib(1)=1,fib(2)=1,fib(3)=fib(3-1)+fib(3-2)=2,fib(4)=fib(4-1)+fib(4-2)=3,所以答案为3。
1
1
2
1
package go.jacob.day1201; /** * 斐波那契数列 * * @author Administrator 记住两个方法:1.O(n)时间复杂度用循环; 2.O(logn)用矩阵相乘 切记不要用递归 */ public class Demo2 { /* * 方法一:循环 时间复杂度O(n) */ public int Fibonacci_1(int n) { if (n < 1) return 0; if (n == 1 || n == 2) return 1; int res = 1; int pre = 1; int tmp = 0; for (int i = 3; i <= n; i++) { tmp = res; res = res + pre; pre = tmp; } return res; } /* * 结论:F(n)=F(n-1)+F(n-2),是一个二阶递推数列, * 一定可以用矩阵乘法的形式表示 * 这道题的递推矩阵为[1,1;1,0] */ public int Fibonacci_2(int n) { if (n < 1) return 0; if (n == 1 || n == 2) return 1; int[][] base = { { 1, 1 }, { 1, 0 } }; int[][] res = maxtrixPower(base, n - 2); return res[0][0] + res[0][1]; } /* * 求矩阵m的p次方 */ private int[][] maxtrixPower(int[][] m, int p) { int[][] res = new int[m.length][m.length]; for (int i = 0; i < m.length; i++) { res[i][i] = 1; } int[][] tmp = m; for (; p != 0; p >>= 1) { if ((p & 1) != 0) { res = multiMatrix(res, tmp); } tmp = multiMatrix(tmp, tmp); } return res; } /* * 求两个矩阵相乘 */ public int[][] multiMatrix(int[][] m1, int[][] m2) { 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 < m1[0].length; k++) { res[i][j] += m1[i][k] * m2[k][j]; } } } return res; } }
public class Solution { public int Fibonacci(int n) { if (n <= 2) return 1; else return Fibonacci(n - 1) + Fibonacci(n - 2); } }
class Solution: def Fibonacci(self , n: int) -> int: # write code here if n == 0: return 0 if n == 1: return 1 return self.Fibonacci(n-1)+self.Fibonacci[n-2]
class Solution: def __init__(self): self.memo=[0] def Fibonacci(self , n: int) -> int: # write code here if n == 0: return 0 if n == 1: self.memo.append(1) return 1 res =self.Fibonacci(n-1)+self.memo[n-2] self.memo.append(res) return res
public class Solution { public int Fibonacci(int n) { int a = 1; int b = 1; while (n-- > 2) { b += a; a = b - a; } return b; } }
const int MAXN=100; class Solution { public: long long f[MAXN]; bool visit[MAXN]; long long Fibonacci(int n){ f[0]=0; f[1]=1; visit[0]=visit[1]=true; if(visit[n]){ return f[n]; } f[n]=Fibonacci(n-2)+Fibonacci(n-1); visit[n]=true; return f[n]; } };
public class Solution { public int Fibonacci(int n) { if(n == 0) return 0; int a = 1; int b = 1; for(int i = 2; i < n; i++){ a = a + b; b = a - b; } return a; } }
# -*- coding:utf-8 -*- class Solution: def Fibonacci(self, n): if n==0: return 0; if n==1: return 1; if n>=2: f_list = [0,1] for i in range(2,n+1,1): ai = f_list[i-1] + f_list[i-2] f_list.append(ai) return f_list[-1]
func Fibonacci( n int ) int { // write code here if(n < 2){ return n; } tail := 0 head := 1 for i := 2; i <= n; i++ { tail, head = head, tail + head } return head }