[英]Why does Memoization not work here, and how can I make it work?
class Solution {
public:
int n, memo[101];
int minCost(vector<vector<int>>& costs) {
n = costs.size();
memset(memo, -1, sizeof(memo));
return dfs(costs, 0, true, true, true);
}
int dfs(vector<vector<int>>& costs, int idx, bool red, bool green, bool yellow) {
if (idx == n) {
return 0;
}
if (memo[idx] != -1) {
return memo[idx];
}
int a = 1e9, b = 1e9, c = 1e9;
if (red == true)
a = dfs(costs, idx + 1, false, true, true) + costs[idx][0];
if (green == true)
b = dfs(costs, idx + 1, true, false, true) + costs[idx][1];
if (yellow == true)
c = dfs(costs, idx + 1, true, true, false) + costs[idx][2];
return memo[idx] = min({a, b, c});
}
};
我為上述問題創建了一個遞歸解決方案,但由於該解決方案的效率極低 O(3^N),我想將記憶添加到我的遞歸 function 中,這樣它就不會調用重疊的子問題。 我相信我實施不正確,因為它在應用記憶后給出了錯誤的 output。 我做錯什么了?
問題是你只根據你有多深來記憶( idx
總是適合你)嘗試使用整個 state 來記憶。 例如將所有memo[idx]
切換為memo[8*idx+4*red+2*green+blue]
同時將memo
的大小調整 8 次到n
+8 的最大可能值(如果 n<=100 則應為 808)
假設您現在唯一的問題是記憶,這應該可以解決
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.