在 n=1000 之前堆栈溢出。是因为对 long[] 参数的引用,JVM 觉得需要保留每个堆栈帧(疯狂猜测),还是我做错了什么?
public static void main(String[] args) {
long start = System.currentTimeMillis();
fibonacciMemoized(1000);
long end = System.currentTimeMillis();
System.out.println("\nTotal run time: " + (end-start));
}
public static void fibonacciMemoized(int n) {
long[] fibMemos = new long[n+1];
for (int i = 0; i < fibMemos.length; i++) {
fibMemos[i] = Long.MAX_VALUE;
}
long fibResult = fib(n, 1, 0, fibMemos);
System.out.println(fibResult);
}
public static long fib(int n, long fibAcc, long fibPrev, long[] fibMemos) {
if (fibMemos[n] != Long.MAX_VALUE){
return fibMemos[n];
} else if (n == 0) {
return fibPrev;
} else if (n == 1){
return fibAcc;
} else {
long result = fib(n-1, fibAcc+fibPrev, fibAcc, fibMemos);
fibMemos[n] = result;
return result;
}
}