- 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 C++ from the credited upstream file 2184.cpp.
- 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:3 int buildWall(int height, int width, vector<int>& bricks) {4 constexpr int kMod = 1'000'000'007;5 6 vector<int> rows;7 buildRows(width, bricks, 0, rows);8 9 const int n = rows.size();10 11 12 vector<long> dp(n, 1);13 14 vector<vector<int>> graph(n);15 16 for (int i = 0; i < n; ++i)17 for (int j = 0; j < n; ++j)18 if (!(rows[i] & rows[j]))19 graph[i].push_back(j);20 21 for (int h = 2; h <= height; ++h) {22 vector<long> newDp(n);23 for (int i = 0; i < n; ++i)24 for (const int v : graph[i]) {25 newDp[i] += dp[v];26 newDp[i] %= kMod;27 }28 dp = std::move(newDp);29 }30 31 return accumulate(dp.begin(), dp.end(), 0L) % kMod;32 }33 34 private:35 void buildRows(int width, const vector<int>& bricks, int path,36 vector<int>& rows) {37 for (const int brick : bricks)38 if (brick == width)39 rows.push_back(path);40 else if (brick < width) {41 const int newWidth = width - brick;42 buildRows(newWidth, bricks, path | 1 << newWidth, rows);43 }44 }45};46