LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares

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;
}
相关推荐
labuladong1 小时前
全新的算法 & Agent 课程页上线
算法·llm·agent
leobertlan2 小时前
好玩系列 | 以简构繁,从把玩一把天平进入信息论和编码
算法
电科_银尘2 小时前
【大模型算法与工程 48】项目实战:可调用、可追踪的大模型问答服务
算法
电科_银尘3 小时前
【大模型算法与工程 47】服务工程:并发、排队、限流与可观测性
算法
西数科技CDRSA3 小时前
BGA封装NAND芯片不识别,Flash Extractor引脚直读还原原始镜像
数据结构·算法·硬件工程
AvocadoZeroOneOI4 小时前
Kadane 算法(最大子段和)
c++·学习·算法·动态规划
Lazyafei7 小时前
滑动窗口:扩张与收缩的动态区间
算法
FRing038 小时前
for循环、while循环、Java高级语法、数组
java·开发语言·后端·算法
老歌老听老掉牙8 小时前
三个等价答案:遗传算法如何逼近 Branin 函数
c++·算法·ga