剑指offer-斐波那契数列
2017-08-23 13:53
274 查看
斐波那契数列:
f(0)=0;
f(1)=1;
f(n)=f(n-1)+f(n-2); (n>1)
通过一个数组把计算过的值存起来,减少因递归操作带来的重复计算。
时间复杂度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))
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))
相关文章推荐
- 剑指offer 斐波那契数列
- 剑指offer-斐波那契数列
- 剑指Offer:斐波那契数列
- 剑指offer(C++)——斐波那契数列
- JAVA实现斐波那契数列问题(《剑指offer》)
- 剑指offer 9---斐波那契数列
- (剑指Offer)面试题9:斐波那契数列
- 剑指offer系列之七:斐波那契数列
- 【剑指offer系列】 斐波那契数列___9
- 剑指offer--找规律题目(斐波那契数列、跳台阶)
- 剑指offer:面试题9,斐波那契数列
- 《剑指offer》之斐波那契数列
- 剑指offer面试题9 斐波那契数列
- 剑指offer(斐波那契数列)
- 剑指offer:面试题9,斐波那契数列
- 《剑指offer》---旋转数组中的最小数字 和 斐波那契数列
- 剑指offer(七)斐波那契数列
- 剑指Offer面试题10:斐波那契数列
- 剑指offer系列之7:斐波那契数列
- 剑指offer(八)之斐波那契数列