题目
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)n≤39
- 输入 4
- 返回值 3
一 递归实现
public static void main(String[] args) {
int inputNum = 39;
System.out.println(Fibonacci(inputNum));
}
/**
* 递归实现
* 时间复杂度 O(n方)
* 空间复杂度 O(1)
*
* @param n
* @return
*/
public static int Fibonacci(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
- 时间复杂度 O(n²)
- 空间复杂度:O(1)
二 优化递归
static HashMap<Integer, Integer> hashMap = new HashMap<>();
/**
* 优化递归调用 记录每次算出的和给后面计算使用
*
* @param n
* @return
*/
public static int Fibonacci1(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
int left1;
int pos1 = n - 1;
if (hashMap.get(pos1) != null && hashMap.get(pos1) > 0) {
left1 = hashMap.get(pos1);
} else {
left1 = Fibonacci(pos1);
hashMap.put(pos1, left1);
}
int left2;
int pos2 = n - 2;
if (hashMap.get(pos2) != null && hashMap.get(pos2) > 0) {
left2 = hashMap.get(pos2);
} else {
left2 = Fibonacci(pos2);
hashMap.put(pos2, left2);
}
return left1 + left2;
}
- 时间复杂度 O(n)
- 空间复杂度:O(n)
三 优化存储
public static int Fibonacci2(int n) {
int[] nums = new int[40];
nums[0] = 0;
nums[1] = 1;
for (int i = 2; i <= n; i++) {
nums[i] = nums[i - 1] + nums[i - 2];
}
return nums[n];
}
- 时间复杂度 O(n)
- 空间复杂度:O(n)
四 持续优化
/**
* 时间复杂度 O(n)
* 空间复杂度 O(1)
*
* @param n
* @return
*/
public static int Fibonacci3(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
int sum = 0; //当前存储的第n项的值
int a = 1; //当前n-1的值
int b = 0;//当前n-2的值
for (int i = 2; i <= n; i++) {
sum = a + b;
b = a;
a = sum;
}
return sum;
}
- 时间复杂度 O(n)
- 空间复杂度:O(1)