【LeetCode 1240】 Tiling a Rectangle with the Fewest Squares

题目描述

Given a rectangle of size n x m, find the minimum number of integer-sided squares that tile the rectangle.

Example 1:

Input: n = 2, m = 3
Output: 3

Example 2:

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

Example 3:

Input: n = 11, m = 13
Output: 6

Constraints:

1 <= n <= 13
1 <= m <= 13

思路

dfs,用 0~n 每一列当前的高度标记状态,每次从最低位置开始填充,从能够填充的最大尺度到1遍历。

代码

class Solution {
public:
    int tilingRectangle(int n, int m) {
       if (n > m) return tilingRectangle(m, n);
        vector<int> h(n, 0);
        int* ans = new int(n*m);
        dfs(n, m, 0, ans, h);
        return *ans;
    }
    
    void dfs(int n, int m, int cnt, int* ans, vector<int>& h) {
        if (cnt >= *ans) {
            return;
        }
        auto it = min_element(begin(h), end(h));
        if (*it == m) {
            *ans = cnt;
            return;
        }
        
        int low = *it;
        int st = it - begin(h);
        int ed = st;
        while(ed < n && h[ed] == h[st] && (ed - st + 1 + low) <= m) ++ed;
        for (int i=--ed; i>=st; --i) {
            int size = i - st + 1;
            for (int j=st; j<=i; ++j) h[j] += size;
            dfs(n, m, cnt+1, ans, h);
            for (int j=st; j<=i; ++j) h[j] -= size;
        }
        
        return;
    }
};
发布了243 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104368008