您的位置:首页 > Web前端

剑指offer-斐波那契数列

2017-08-23 13:53 274 查看
斐波那契数列:

f(0)=0;

f(1)=1;

f(n)=f(n-1)+f(n-2); (n>1)

public class 面试题10 {
static long[] f;
public static long method1(int n) {
if (f
!= 0)
return f
;
if (n <= 1)
return f
;
else {
System.out.println("计算f[" + n + "]");
return f
= method1(n - 1) + method1(n - 2);
}
}

public static void main(String[] args) {
f = new long[1000];
f[0] = 0;
f[1] = 1;
System.out.println("f[100]=" + method1(100));
}
}


通过一个数组把计算过的值存起来,减少因递归操作带来的重复计算。

时间复杂度O(n)

一个通过快速幂思想时间复杂度为O(logn)的算法。

由f(n)=f(n-1)+f(n-2); (n>1) 得:



因f(1),f(0)已知,把求f(n)转化为求(n-1)次方的矩阵问题。

乘方计算有二分的性质:

当n为奇数: a^n=a^((n-1)/2)*a^((n-1)/2)*a;

当n为偶数: a^n=a^(n/2)*a^(n/2);

计算a^n次方只需计算log(n)次,将时间复杂度降为O(log(n))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: