题解:
1.Top-Down Approach using Memoization(自顶向下备忘录法)
Check if N <= 1. If it is, return N.
Call and return memoize(N)
If N exists in the map, return the cached value for N
Otherwise set the value of N, in our mapping, to the value of memoize(N-1) + memoize(N-2)
如求f(5),则本应调用f(4)和f(3),但求f(4)的过程中也会把f(3)求出来,保存在备忘录中,所以求f(5)时就不需要再次调用f(3),直接返回f(3)的值,即catch[3]
class Solution {
private Integer[] cache = new Integer[31];//定义一个存放斐波那契数的数组
public int fib(int N) {
if (N <= 1) {
return N;
}
cache[0] = 0;
cache[1] = 1;
return memoize(N);
}
public int memoize(int N) {
if (cache[N] != null) {
return cache[N]; //如果某个N对应的斐波那契数已经求过了,那直接返回该数,不用再进入该N对应的递归树中
}
cache[N] = memoize(N-1) + memoize(N-2);
return memoize(N); //用备忘录记录求过的解
}
}
2.Bottom-Up Approach using Memoization
Algorithm
If N is less than or equal to 1, return N
Otherwise, iterate through N, storing each computed answer in an array along the way.
Use this array as a reference to the 2 previous numbers to calculate the current Fibonacci number.
Once we’ve reached the last number, return it’s Fibonacci number.
如想求出N=5时对应的斐波那契数,则从N=1时开始求起f(1),f(2)…一直求到f(5)
class Solution {
public int fib(int N) {
if (N <= 1) {
return N;
}
return memoize(N);
}
public int memoize(int N) {
int[] cache = new int[N + 1];
cache[1] = 1;
for (int i = 2; i <= N; i++) {
cache[i] = cache[i-1] + cache[i-2];
}
return cache[N];
}
}
3.Iterative Top-Down Approach
class Solution {
public int fib(int N) {
if (N <= 1) {
return N;
}
if (N == 2) {
return 1;
}
int current = 0;
int prev1 = 1;
int prev2 = 1;
for (int i = 3; i <= N; i++) {
current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
return current;
}
}