- 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
- 46 lines of Java from the credited upstream file 3359.java.
- The implementation visibly relies on sequence storage, work queue, cached states.
- 4 loop blocks 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 long countSubmatrices(int[][] grid, int k) {3 record T(int subarrayWidth, int rowIndex, int accumulatedSubmatrices) {}4 final int m = grid.length;5 final int n = grid[0].length;6 long ans = 0;7 8 int[][] dp = new int[m][n];9 10 11 12 List<Deque<T>> stacks = new ArrayList<>(n);13 14 for (int j = 0; j < n; ++j) {15 Deque<T> stack = new ArrayDeque<>();16 stack.push(new T(0, -1, 0));17 stacks.add(stack);18 }19 20 for (int i = 0; i < m; ++i)21 for (int j = 0; j < n; ++j)22 if (grid[i][j] > k) {23 stacks.get(j).clear();24 stacks.get(j).push(new T(0, i, 0));25 } else {26 dp[i][j] = 1;27 if (j > 0 && grid[i][j - 1] <= k && grid[i][j - 1] >= grid[i][j])28 29 dp[i][j] += dp[i][j - 1];30 final int width = dp[i][j];31 32 33 Deque<T> stack = stacks.get(j);34 while (!stack.isEmpty() && width < stack.peek().subarrayWidth)35 stack.pop();36 final int height = i - stack.peek().rowIndex;37 final int newSubmatrices = width * height;38 final int accumulatedSubmatrices = stack.peek().accumulatedSubmatrices + newSubmatrices;39 ans += accumulatedSubmatrices;40 stack.push(new T(width, i, accumulatedSubmatrices));41 }42 43 return ans;44 }45}46