【发布时间】:2019-07-03 23:15:47
【问题描述】:
我尝试了一个递归斐波那契方法的记忆,它返回了正确的数字。但是,它并没有比以前更快。我假设这是因为我没有正确利用数组来跟踪,而且我仍在进行冗余调用。您能告诉我要更改什么以便我可以正常使用吗?
不确定是否重要,但fibIndex[]在全局区域中声明,并在获取输入后在main方法中设置为[index + 1]的长度。
public static BigInteger fibRec(int index)
{
BigInteger results;
if (index <= 2)
{
results = BigInteger.ONE;
}
else
{
if (fibIndex[index] != null)
{
results = fibIndex[index];
}
else
{
results = fibRec(index - 1).add(fibRec(index - 2));
}
}
return results;
}
【问题讨论】:
标签: java recursion fibonacci biginteger memoization