斐波拉契数列
作者:互联网
求取斐波拉契数列第N位的值
斐波拉契数列:每一位的值等于他前两位数字的和。前两位固定
0、1、1、2、3、5、8、13...
public class Fib {
public static void main(String[] args) {
System.out.println(calculate1(10));
System.out.println(calculate2(10));
System.out.println(calculate3(10));
}
//暴力递归
public static int calculate1(int num){
if (num==0){
return 0;
}
if (num==1){
return 1;
}
return calculate1(num-1)+calculate1(num-2);
}
//改进
public static int calculate2(int num){
int[] arr = new int[num+1];
return recurse(arr,num);
}
private static int recurse(int arr[],int num){
if (num==0){
return 0;
}
if (num==1){
return 1;
}
if(arr[num] != 0){
return arr[num];
}
arr[num] = recurse(arr,num-1)+recurse(arr,num-2);
return arr[num];
}
//双指针
public static int calculate3(int num){
int low=0,high=1;
if (num==0){
return 0;
}
if (num==1){
return 1;
}
for (int i=1;i<num;i++){
int sum = low+high;
low = high;
high = sum;
}
return high;
}
}
标签:arr,return,数列,int,波拉,num,static,public 来源: https://www.cnblogs.com/cfs322/p/15074702.html