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;
}
相关推荐
Zwawa25 分钟前
嵌入式OLED表驱动菜单:用一张表、一个栈和一个窗口重写表驱动菜单
c语言·单片机·嵌入式
Oneshot2 小时前
DLX(Dancing Links)算法详解:求解数独最快的算法
算法
文丑颜不良啊2 小时前
LeetCode2541~2560题目解析
java·leetcode
青少儿编程课堂2 小时前
蓝桥杯青少组图形化 + 全国青少年信息素养大赛 + 电子学会Scratch考级:校园连连看解析
c++·python·算法·bfs·信息学竞赛
kongdong3 小时前
Hikyuu | RSI均值回归交易策略实现
算法·均值算法·回归·量化交易·交易策略·hikyuu
小王C语言3 小时前
优选算法:分治-归并排序
算法
非优秀程序员13 小时前
第05章 播放器大战,暴风、快播与那一夜|《互联网产品恩仇录》
算法
沐晓时光14 小时前
C语言入门,内存函数知识讲解
c语言·开发语言
文丑颜不良啊16 小时前
LeetCode2481~2500题目解析
java·leetcode