- 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
- 45 lines of Java from the credited upstream file 2184.java.
- The implementation visibly relies on sequence storage, cached states.
- 6 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 int buildWall(int height, int width, int[] bricks) {3 final int MOD = 1_000_000_007;4 5 List<Integer> rows = new ArrayList<>();6 buildRows(width, bricks, 0, rows);7 8 final int n = rows.size();9 10 long[] dp = new long[n];11 12 List<Integer>[] graph = new List[n];13 14 Arrays.fill(dp, 1);15 Arrays.setAll(graph, i -> new ArrayList<>());16 17 for (int i = 0; i < n; ++i)18 for (int j = 0; j < n; ++j)19 if ((rows.get(i) & rows.get(j)) == 0)20 graph[i].add(j);21 22 for (int h = 2; h <= height; ++h) {23 long[] newDp = new long[n];24 for (int i = 0; i < n; ++i)25 for (final int v : graph[i]) {26 newDp[i] += dp[v];27 newDp[i] %= MOD;28 }29 dp = newDp;30 }31 32 return (int) (Arrays.stream(dp).sum() % MOD);33 }34 35 private void buildRows(int width, int[] bricks, int path, List<Integer> rows) {36 for (final int brick : bricks)37 if (brick == width)38 rows.add(path);39 else if (brick < width) {40 final int newWidth = width - brick;41 buildRows(newWidth, bricks, path | 1 << newWidth, rows);42 }43 }44}45