- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 53 lines of C++ from the credited upstream file 1931.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 1 loop block detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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 colorTheGrid(int m, int n) {4 this->m = m;5 this->n = n;6 return dp(0, 0, 0, 0);7 }8 9 private:10 static constexpr int kMod = 1'000'000'007;11 int m;12 int n;13 vector<vector<int>> mem = vector<vector<int>>(1000, vector<int>(1024));14 15 int dp(int r, int c, int prevColMask, int currColMask) {16 if (c == n)17 return 1;18 if (mem[c][prevColMask])19 return mem[c][prevColMask];20 if (r == m)21 return dp(0, c + 1, currColMask, 0);22 23 int ans = 0;24 25 26 for (int color = 1; color <= 3; ++color) {27 if (getColor(prevColMask, r) == color)28 continue;29 if (r > 0 && getColor(currColMask, r - 1) == color)30 continue;31 ans += dp(r + 1, c, prevColMask, setColor(currColMask, r, color));32 ans %= kMod;33 }34 35 if (r == 0)36 mem[c][prevColMask] = ans;37 38 return ans;39 }40 41 42 43 44 45 int getColor(int mask, int r) {46 return mask >> r * 2 & 3;47 }48 49 int setColor(int mask, int r, int color) {50 return mask | color << r * 2;51 }52};53