[英]Memoization of recursive Fibonacci method not faster?
我嘗試了遞歸斐波那契方法的記憶,它返回正確的數字。 但是,它似乎沒有比以前更快。 我以為這是因為我沒有正確利用數組來跟蹤,而我仍在進行冗余調用。 您能告訴我要進行哪些更改,以便我可以正確使用它嗎?
不確定是否重要,但是在全局區域中聲明了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;
}
它沒有運行得更快,因為您實際上沒有使用備忘錄,即沒有將結果放入數組中。 如果您不這樣做,那么您的實現實際上會變慢 ,因為您一直在檢查從未真正記憶的記憶結果。 這是您需要做的。
public static BigInteger fibRec(int index) {
if (index <= 2) return BigInteger.ONE;
BigInteger result = fibIndex[index];
if (result == null) {
result = fibRec(index - 1).add(fibRec(index - 2));
fibIndex[index] = result; // you forgot this
}
return result;
}
編輯:我在這里早些時候記下有關您不需要為只調用一次的方法的記憶,但后來我記得該方法是遞歸的。 因此,請忘記我之前在這里說過的內容,記住實際上可以大大加快該方法的速度。
我注意到您實際上並沒有在任何地方填寫fibIndex
。 基於此,您的if語句條件何時觸發?
這使您對要解決的問題有感覺嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.