斐波那契数列(递归)

来源:LeetCode

 

看到递归体都给了,直接放上去跑

public int fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n-1) + fib(n - 2)%1000000007;
}
结果超出时间限制,时间复杂度为2的n次方。

由于每一次计算都是重复的,那么我们只需要避免重复的计算,使空间复杂度为O(N)

 

 

 

优化后

public int fib(int n) {
int[] MEMO = new int[n+1];
Arrays.fill(MEMO, -1);
return Recursion(n, MEMO)%1000000007;
}

public int Recursion(int num, int[] MEMO) {
//递归出口
if (num <= 1) {
return num;
}
//未计算过的
if (MEMO[num] == -1) {
MEMO[num] = Recursion(num - 1, MEMO) + Recursion(num - 2, MEMO);
}
//计算过的
return MEMO[num]%1000000007;
}

public static void main(String[] args) {
Fibonacci2 fibonacci2 = new Fibonacci2();
System.out.println(fibonacci2.fib(10));
}

 

 


 

posted @ 2021-12-14 23:14  Wavve  阅读(214)  评论(0)    收藏  举报