- 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
- 47 lines of C++ from the credited upstream file 1595.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks 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 connectTwoGroups(vector<vector<int>>& cost) {4 const int m = cost.size();5 const int n = cost[0].size();6 vector<vector<int>> mem(m, vector<int>(1 << n, INT_MAX));7 8 vector<int> minCosts(n);9 10 for (int j = 0; j < n; ++j) {11 int minCostIndex = 0;12 for (int i = 1; i < m; ++i)13 if (cost[i][j] < cost[minCostIndex][j])14 minCostIndex = i;15 minCosts[j] = cost[minCostIndex][j];16 }17 18 return connectTwoGroups(cost, 0, 0, minCosts, mem);19 }20 21 private:22 23 24 int connectTwoGroups(const vector<vector<int>>& cost, int i, int mask,25 const vector<int>& minCosts, vector<vector<int>>& mem) {26 if (i == cost.size()) {27 28 29 int res = 0;30 for (int j = 0; j < cost[0].size(); ++j)31 if ((mask >> j & 1) == 0)32 res += minCosts[j];33 return res;34 }35 if (mem[i][mask] != INT_MAX)36 return mem[i][mask];37 38 for (int j = 0; j < cost[0].size(); ++j)39 mem[i][mask] =40 min(mem[i][mask],41 cost[i][j] +42 connectTwoGroups(cost, i + 1, mask | 1 << j, minCosts, mem));43 44 return mem[i][mask];45 }46};47