我正在嘗試創建階乘函數的memoized版本。當我調用factMemoized(4)時,它首次計算4的階乘因子並將其存儲在Map中。當我再次調用factMemoized(4)時,它現在給出了存儲的結果,而不是再次重新計算它。這按預期工作。但是,當我將factMemoized(3)稱爲factMemoized(3)時,它會重新計算這個值,儘管它已經將事實(3)計算爲計算事實(4)的一部分。有沒有什麼方法可以確保即使作爲遞歸調用的一部分計算出的值將被存儲在地圖中,而無需在fact()函數中添加memoization函數?遞歸方法的Java記憶
import java.util.HashMap;
import java.util.Map;
public class MemoizeBetter {
public static <F, T> Function<F, T> memoize(final Function<F, T> inputFunction) {
return new Function<F, T>() {
// Holds previous results
Map<F, T> memoization = new HashMap<F, T>();
@Override
public T apply(final F input) {
// Check for previous results
if (!memoization.containsKey(input)) {
// None exists, so compute and store a new one
memoization.put(input, inputFunction.apply(input));
}else{
System.out.println("Cache hit:"+input);
}
// At this point a result is guaranteed in the memoization
return memoization.get(input);
}
};
}
public static void main(String args[]){
final Function<Integer, Integer> fact = new Function<Integer, Integer>() {
@Override
public Integer apply(final Integer input) {
System.out.println("Fact: " + input);
if(input == 1)
return 1;
else return input * apply(input -1);
}
};
final Function<Integer, Integer> factMemoized = MemoizeBetter.memoize(fact);
System.out.println("Result:"+ factMemoized.apply(1));
System.out.println("Result:"+factMemoized.apply(2));
System.out.println("Result:"+factMemoized.apply(3));
System.out.println("Result:"+factMemoized.apply(2));
System.out.println("Result:"+factMemoized.apply(4));
System.out.println("Result:"+factMemoized.apply(1)); }
}
interface Function<F,T>{
T apply(F input);
}
記憶地圖正在被覆蓋,即(0,4),它會覆蓋到相同的索引(0,3),確保你的邏輯是正確。 –