// 尚未增加状态记忆剪枝 // 相同状态出现时,若该状态已经能达到的值小于等于当前值则剪枝 // long key = 0, base = m + 1; // for (int i = 1; i <= n; i++) { // key += h[i] * base; // base *= m + 1; // } classSolution { public: inttilingRectangle(int n, int m){ if (n == m) return1; if (n > m) swap(n, m); vector<int> h(n, 0); int ans = 13*13; dfs(ans, 0, h, m, n); return ans; } voiddfs(int &ans, int cur, vector<int> &h, int m, int n){ if (cur >= ans) return; int pos = 0; for (int i = 0; i < n; ++i) if (h[i] < h[pos]) pos = i;
if (h[pos] == m) { ans = min(ans, cur); return; } int e = pos; while (e < n && h[e] == h[pos] && h[pos]+e-pos+1 <= m) e++; for (int i = --e; i >= pos; --i) { int add = i-pos+1; for (int j = pos; j <= i; ++j) { h[j] += add; } dfs(ans, cur+1, h, m, n); for (int j = pos; j <= i; ++j) { h[j] -= add; } } return; } };