- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 39 lines of C++ from the credited upstream file 1473.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minCost(vector<int>& houses, vector<vector<int>>& cost, int m, int n,4 int target) {5 vector<vector<vector<int>>> mem(target + 1,6 vector<vector<int>>(m, vector<int>(n + 1)));7 8 const int c = minCost(houses, cost, m, n, target, 0, 0, mem);9 return c == kMax ? -1 : c;10 }11 12 private:13 static constexpr int kMax = 1'000'001;14 15 16 17 int minCost(const vector<int>& houses, const vector<vector<int>>& cost,18 const int& m, const int& n, int k, int i, int prevColor,19 vector<vector<vector<int>>>& mem) {20 if (i == m || k < 0)21 return k == 0 ? 0 : kMax;22 if (mem[k][i][prevColor] > 0)23 return mem[k][i][prevColor];24 if (houses[i] > 0) 25 return minCost(houses, cost, m, n, k - (prevColor != houses[i]), i + 1,26 houses[i], mem);27 28 int res = kMax;29 30 31 for (int color = 1; color <= n; ++color)32 res = min(res, cost[i][color - 1] + minCost(houses, cost, m, n,33 k - (prevColor != color),34 i + 1, color, mem));35 36 return mem[k][i][prevColor] = res;37 }38};39