- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 47 lines of C++ from the credited upstream file 1240.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 4 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 tilingRectangle(int n, int m) {4 unordered_map<long, int> mem;5 return tilingRectangle(n, m, 0, vector<int>(m), mem);6 }7 8 private:9 static constexpr int kBase = 13;10 11 int tilingRectangle(int n, int m, long hashedHeights, vector<int>&& heights,12 unordered_map<long, int>& mem) {13 if (const auto it = mem.find(hashedHeights); it != mem.cend())14 return it->second;15 16 const auto it = ranges::min_element(heights);17 const int minHeight = *it;18 if (minHeight == n) 19 return 0;20 21 int ans = m * n;22 const int start = it - heights.begin();23 24 for (int sz = 1; sz <= min(m - start, n - minHeight); ++sz) {25 26 if (heights[start + sz - 1] != minHeight)27 break;28 29 for (int i = start; i < start + sz; ++i)30 heights[i] += sz;31 ans = min(ans,32 tilingRectangle(n, m, hash(heights), std::move(heights), mem));33 for (int i = start; i < start + sz; ++i)34 heights[i] -= sz;35 }36 37 return mem[hashedHeights] = 1 + ans;38 }39 40 long hash(const vector<int>& heights) {41 long hashed = 0;42 for (int i = heights.size() - 1; i >= 0; --i)43 hashed = hashed * kBase + heights[i];44 return hashed;45 }46};47