奇怪的是,这个问题有 0 个赞,但有 4 个答案,我觉得其中没有一个真正令人满意。这是使用 4 种不同方法并进行比较的实现 + 测试示例:
import java.util.ArrayList;
import java.util.HashMap;
public class Fib {
// Straightforward implementation:
public static int fib(int n) {
if (n <= 1) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
// Using array:
static int[] memoArray;
public static int fibArray(int n) {
memoArray = new int[n];
return fibArrayHelper(n);
}
private static int fibArrayHelper(int n) {
if (n <= 1) {
return n;
} else {
if (memoArray[n - 2] != 0) {
return memoArray[n - 2];
}
memoArray[n - 2] = fibArrayHelper(n - 2) + fibArrayHelper(n - 1);
return memoArray[n - 2];
}
}
// Using ArrayList:
static ArrayList < Integer > memoArrayList = new ArrayList < Integer > ();
public static int fibArrayList(int n) {
return fibArrayListHelper(n);
}
private static int fibArrayListHelper(int n) {
if (n <= 1) {
return n;
} else {
if (n - 2 < memoArrayList.size())
return memoArrayList.get(n - 2);
else {
memoArrayList.add(fibArrayListHelper(n - 2) + fibArrayListHelper(n - 1));
return memoArrayList.get(n - 2);
}
}
}
// Using HashMap:
static HashMap < Integer, Integer > memoHash = new HashMap < Integer, Integer > ();
static public int fibHashMap(int n) {
if (n <= 1)
return n;
if (memoHash.get(n) == null) {
memoHash.put(n - 2, fibHashMap(n - 1) + fibHashMap(n - 2));
}
return memoHash.get(n - 2);
}
public static void main(String args[]) {
long preTime, postTime;
int x = 35;
preTime = System.nanoTime();
System.out.printf("%17s: %d", "fib(" + x + ")", fib(x));
postTime = System.nanoTime();
System.out.printf(", computed in %10d nanoseconds.\n", postTime - preTime);
preTime = System.nanoTime();
System.out.printf("%17s: %d", "fibArray(" + x + ")", fibArray(x));
postTime = System.nanoTime();
System.out.printf(", computed in %10d nanoseconds.\n", postTime - preTime);
preTime = System.nanoTime();
System.out.printf("%17s: %d", "fibArrayList(" + x + ")", fibArrayList(x));
postTime = System.nanoTime();
System.out.printf(", computed in %10d nanoseconds.\n", postTime - preTime);
preTime = System.nanoTime();
System.out.printf("%17s: %d", "fibHashMap(" + x + ")", fibHashMap(x));
postTime = System.nanoTime();
System.out.printf(", computed in %10d nanoseconds.\n", postTime - preTime);
}
}