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});
}
};
I created a recursive solution to the problem above, but since the solution is extremally inefficient O(3^N), I wanted to add memoization to my recursive function so it doesn't call overlapping sub problems. I believe I implemented it incorrectly since it gives the wrong output after applying memoization. What did I do wrong?