我有一个程序,可以用递归方法计算第n个斐波那契数,同时使用记忆法。
当我达到n= 11000左右时,我得到了一个堆栈溢出异常。有人能帮我解决这个问题吗?
下面是我的代码:
public class BigInt {
static BigInteger[] fval;
public static void main(String[] args) {
int index;
Scanner input = new Scanner(System.in);
index = input.nextInt();
fval = new BigInteger[index + 1];
System.out.println(fib_rec(index));
}
public static BigInteger fib_rec(int index) {
BigInteger result = BigInteger.ONE;
if (index <= 2) {
return result;
} else {
if (fval[index] != null) {
result = fval[index];
} else {
result = fib_rec(index - 1).add(fib_rec(index - 2));
fval[index] = result;
}
return result;
}
}
发布于 2017-09-09 03:28:44
你的记忆不会改变递归的深度...在对fib_rec(n)
的调用中,它调用fib_rec(n-1)
,后者调用fib_rec(n-2)
等。如果你颠倒了调用的顺序(所以你做了fib_rec(index - 2).add(fib_rec(index - 1))
,这应该允许你把堆栈深度减少大约一半,因为你会一直工作到根目录,然后根据你的记忆,从下往上填入堆栈深度为1的空白。
然而,如果不对算法进行更戏剧性的重写,就无法避免堆栈深度问题。
https://stackoverflow.com/questions/46123150
复制相似问题