public class Test4 {
/*
* 3种方法根据排序依次按照时间复杂度和空间复杂度有高到低
* */
//斐波那契
//0,1,1,2,3,5,8,13,21,34,55........除了前2个为定死的0和1 以后的每个数字都是后2个数相加之和 求第n个下标的数字是多少
public static void main(String[] args) {
int oneMethod = oneMethod(10);
System.out.println(oneMethod);
int twoMethod = twoMethod(10);
System.out.println(twoMethod);
int threeMethod = threeMethod(10);
System.out.println(threeMethod);
}
//第一种(暴力遍历)
private static int oneMethod(int num){
if(num == 0){
return 0;
}else if(num == 1){
return 1;
}
return oneMethod(num-1) + oneMethod(num - 2);
}
//第二种(存放数组单边遍历)
private static int twoMethod(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;
}else if(num == 1){
return 1;
}
if(arr[num] != 0){
return arr[num];
}
return recurse(arr,num-1) + recurse(arr,num - 2);
}
//第三种(高低指针)
private static int threeMethod(int num){
if(num == 0){
return 0;
}else if(num == 1){
return 1;
}
int low = 0,hight = 1;
for (int i = 2; i <= num; i++) {
int sum = low + hight;
low = hight;
hight = sum;
}
return hight;
}
}