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
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 <= 13
  • 1 <= m <= 13

思路:参考https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/discuss/414260/8ms-Memorized-Backtrack-Solution-without-special-case!

往横轴方向看去,每个位置都要达到纵轴的高度

然后找到最短的地方,然后dfs遍历在最短地方添加的正方形大小

然后注意优先遍历填充大的正方形

class Solution(object):
    def tilingRectangle(self, n, m):
        """
        :type n: int
        :type m: int
        :rtype: int
        """
        res = [n*m]
        def dfs(hs, cnt):
            if cnt>=res[0]: return 
            if min(hs)==n: 
                res[0]=min(res[0],cnt)
                return
            minIdx = hs.index(min(hs))
            minIdxEnd = minIdx
            while minIdxEnd+1<m and hs[minIdxEnd+1]==hs[minIdx]: minIdxEnd+=1
            span = min(n-min(hs), minIdxEnd-minIdx+1)
            for i in range(span,0,-1):
                hs2 = list(hs)
                for j in range(minIdx, minIdx+i): hs2[j]+=i
                dfs(hs2, cnt+1)
        dfs([0]*m, 0)
        return res[0]
    

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值