/**
* 斐波拉契数
*/
public class Fibonacci {
// 普通算法
public static int fab(int n ){
if (n <= 2){
return 1;
}
return fab(n-1) + fab(n-2);
}
// 非递归算法 // 不用递归 O(n)
public static int fabFor(int n ){
if (n <= 2){
return 1;
}
int f1 = 1;
int f2 = 1;
int now = 0;
for (int i =3; i <= n; i++){
now = f1 + f2;
f1 = f2;
f2 = now;
}
return now;
}
// 用数组来做缓存 将为了O(n),空间也降至为O(n)
public static int[] map = new int[n];
public static int fabMap(int n ){
if (n <= 2){
return 1;
}
if (map[n] >0){
return map[n];
}
int res = fabMap(n-1) + fabMap(n-2);
map[n] = res;
return res;
}
/**
* 尾递归
* last 上一次运算出来结果
* beforeLast 上上一次运算出来的结果
*/
public static int tailfab(int beforeLast,int last,int n) {
if (n <= 2)
return last; // 递归的终止条件
return tailfab(last, beforeLast + last, n - 1);
}
}
斐波拉契数多种算法
于 2020-08-08 17:41:19 首次发布
2790

被折叠的 条评论
为什么被折叠?



