- 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
- 51 lines of Java from the credited upstream file 1931.java.
- 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 int colorTheGrid(int m, int n) {3 this.m = m;4 this.n = n;5 return dp(0, 0, 0, 0);6 }7 8 private static final int MOD = 1_000_000_007;9 private int m;10 private int n;11 private int[][] mem = new int[1000][1024];12 13 private int dp(int r, int c, int prevColMask, int currColMask) {14 if (c == n)15 return 1;16 if (mem[c][prevColMask] != 0)17 return mem[c][prevColMask];18 if (r == m)19 return dp(0, c + 1, currColMask, 0);20 21 int ans = 0;22 23 24 for (int color = 1; color <= 3; ++color) {25 if (getColor(prevColMask, r) == color)26 continue;27 if (r > 0 && getColor(currColMask, r - 1) == color)28 continue;29 ans += dp(r + 1, c, prevColMask, setColor(currColMask, r, color));30 ans %= MOD;31 }32 33 if (r == 0)34 mem[c][prevColMask] = ans;35 36 return ans;37 }38 39 40 41 42 43 private int getColor(int mask, int r) {44 return mask >> r * 2 & 3;45 }46 47 private int setColor(int mask, int r, int color) {48 return mask | color << r * 2;49 }50}51