斐波那契序列程序优化
来源:互联网 发布:鳄鱼毒品知乎 编辑:程序博客网 时间:2024/05/01 15:49
最近在看高德纳的<<计算机程序设计艺术>>,其中看到了斐波那契序列。 用代码实现序列非常简单,程序如下:
public static int x(int a) {
if (a <= 0) {
return 0;
}
switch (a) {
case 1:
return 1;
default:
return x(a - 2) + x(a - 1);
}
}
运行程序,序列数据执行也没有问题,然而,将a值设定为50以上之后,发现运行速度非常慢。原因是在递归调用的过程中,大量的重复计算。因为是重复计算,那么就可以通过保存每次计算的结果,来过滤重复计算的问题。程序实现如下:
public static int x2(int a ,Map<Integer,Integer> map){
int result = 0;
if (a >= 0) {
switch (a) {
case 0:
map.put(0, 0);
break;
case 1:
result = 1;
map.put(1, 1);
break;
default:
if(map.isEmpty()){
result = x2(a-1,map)+x2(a-2,map);
map.put(a, result);
}else{
result=map.get(a-1)+map.get(a-2);
}
}
}
return result;
}
以上优化,虽然解决的运行缓慢的问题,但是,带来的问题就是需要O(N)的空间消耗。
查看整个序列,实际上 表达式为 f(x) = f(x-1)+f(x-2) (x>1),因此,我们可以用两个空间来存放f(x-1)和f(x-2)的数值,就能满足序列的执行,附带的空间消耗也将变为O(2)
代码实现如下:
private static int next;
private static int current;
public static int x1(int a) {
int result = 0;
if (a > 0) {
switch (a) {
case 0:
break;
case 1:
result = 1;
break;
default:
result = x1(a - 1) + next;
}
next = current;
current = result;
}
return result;
}
- 斐波那契序列程序优化
- 斐波那契序列
- 斐波那契序列
- 斐波那契序列
- 斐波那契序列
- 斐波那契序列
- 斐波那契序列
- 斐波那契序列
- 优化斐波那契
- 优化斐波那契
- [机房练习赛4.7] 斐波那契子序列 暴力+数据结构优化
- 斐波那契序列 集锦 (转)
- 斐波那契序列集锦(转)
- 斐波那契序列 集锦 (转)
- 斐波那契序列 集锦 (转)
- 斐波那契序列 集锦
- 斐波那契序列 集锦 (转)
- 斐波那契序列(数组)
- Android调用so文件(C代码库)方法详解
- 下拉刷新控件SwipeRefreshLayout用法简介
- 线性规划与网络流24题の1 飞行员配对方案问题(最大匹配)
- dumpsys SurfaceFlinger
- hdu 1874 畅通工程续
- 斐波那契序列程序优化
- PCB设计资料:看到最后才知道是福利
- 老城里斯本简介
- HDU 3255 Farming(线段树求体积并)
- 解决Firefox 27中AutoProxy不能订阅代理规则的方法
- 番外:菜鸟如何读优秀 JS 开源项目之“2048”
- 链表的基本操作
- 数据结构之双链表的基本操作
- linux系统下安装samba,和简单网络配置 .