1. Fibonacci Number
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 …
f[i] = f[i - 1] + f[i - 2]
F[n] =
没什么好说的,有时候记得用高精度
有时候还需要矩阵快速幂
1.递归 时间复杂度O(2^n)
int f(int n){
if(n == 1 || n == 2){
return 1;
}
return f(n - 1) + f(n - 2);
}
2.循环 时间复杂度O(n)
public int f(int n) {
// write code here
int f0 = 1;
int f1 = 1;
int f2 = 0;
for(int i = 2; i < n; i++){
f2 = f0 + f1;
f0 = f1;
f1 = f2;
}
return f2;
}
3.矩阵求解 时间复杂度O(logn)
斐波那契的递推公式可以表示成如下矩阵形式:
根据矩阵的分治算法,可以在O(logn)时间内算出结果。
public class Fibonacci {
static long[][] f = new long[][]{{0,1},{1,1}};
public int getNthNumber(int n) {
if(n == 0)
return 1;
if(n == 1)
return 1;
f = pow(n,f);
return (int) (f[1][1]%1000000007);
}
private long[][] pow(int n,long[][] f){//矩阵的幂函数
if(n == 1)
return f;
if(n == 2)
return fun(f,f);
if((n&1)==0){//偶数
f = pow(n/2,f);
return fun(f, f);
}
else
return fun(pow(n/2,f),pow(n/2 + 1,f));
}
private long[][] fun(long[][] f,long[][] m){
long[][] temp = new long[2][2];
temp[0][0] = (f[0][0]*m[0][0] + f[0][1]*m[1][0]);
temp[0][1] = (f[0][0]*m[0][1] + f[0][1]*m[1][1]);
temp[1][0] = (f[1][0]*m[0][0] + f[1][1]*m[1][0]);
temp[1][1] = (f[1][0]*m[0][1] + f[1][1]*m[1][1])%1000000007;
return temp;
}
}