1240. Tiling a Rectangle with the Fewest Squares
Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.
Example 1:

Input: n = 2, m = 3
Output: 3
Explanation: 3 squares are necessary to cover the rectangle.
2 (squares of 1x1)
1 (square of 2x2)
Example 2:

Input: n = 5, m = 8
Output: 5
Example 3:

Input: n = 11, m = 13
Output: 6
Constraints:
- 1 <= n, m <= 13
From: LeetCode
Link: 1240. Tiling a Rectangle with the Fewest Squares
Solution:
Ideas:
use backtracking with a "height array". Always fill the lowest column first, try the biggest possible square first, and prune when already worse than answer.
Code:
c
int H, W;
int best;
int height[13];
void dfs(int used) {
if (used >= best) return;
int minH = H, pos = -1;
for (int i = 0; i < W; i++) {
if (height[i] < minH) {
minH = height[i];
pos = i;
}
}
if (minH == H) {
best = used;
return;
}
int maxSize = H - minH;
for (int i = pos; i < W && height[i] == minH; i++) {
int width = i - pos + 1;
if (width > maxSize) break;
}
int len = 0;
while (pos + len < W && height[pos + len] == minH && len < maxSize) {
len++;
}
for (int size = len; size >= 1; size--) {
for (int i = pos; i < pos + size; i++) {
height[i] += size;
}
dfs(used + 1);
for (int i = pos; i < pos + size; i++) {
height[i] -= size;
}
}
}
int tilingRectangle(int n, int m) {
H = n;
W = m;
if (H < W) {
int temp = H;
H = W;
W = temp;
}
best = H * W;
for (int i = 0; i < W; i++) {
height[i] = 0;
}
dfs(0);
return best;
}