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;
}
相关推荐
Code_Solitude几秒前
C语言:指针题型总结
c语言·开发语言
wyhwust2 分钟前
程序设计基础-No5课件知识点
c语言
suhan7 分钟前
【数据结构】六、图:4.图的遍历(深度优先算法DFS、广度优先算法BFS)
数据结构·算法·排序算法
suhan7 分钟前
【数据结构】六、图:3.十字链表、邻接多重表、边集数组
数据结构·算法·排序算法
Dola_Zou11 分钟前
工商业储能系统核心策略
算法·自动化·软件工程
Tsuki_tl12 分钟前
【优选算法:双指针】——复写零题解
java·c++·算法·leetcode·数组·双指针·复写零
FLJwu21 分钟前
运动相机采购选型避坑实战|第二篇
c语言·开发语言·数码相机·运动相机·oem 量产
Rain的Java大神之路30 分钟前
面了上百人,我最爱问的LeetCode 1「两数之和」:能背代码的很多,能讲清“先查后存”的没几个
java·后端·算法
Ivanqhz1 小时前
超参数考量与设计
数据库·人工智能·深度学习·算法·机器学习
雪落漂泊1 小时前
C++算法 滑动窗口篇(上)
开发语言·c++·算法