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
往横轴方向看去,每个位置都要达到纵轴的高度
然后找到最短的地方,然后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]