[Leetcode] 1240. Tiling a Rectangle with the Fewest Squares (Hard)

概述

題目

https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/
給定長寬之長方形,求鋪正方形地磚之最少塊數

心得

好難 XD,單純切大的 DP 算有概念,但範例 3 就確認無法解,事後看來這題在週賽出的是考勇氣,Coding 面試若考這題這考官明顯有問題 www,連 lee215 大神都說可能不是很適合,週賽的時候還是直接 cheat XD,故就不糾結此題

DP + corner case

思路

from 花花,因為是 <= 13 且範例 3 是唯二特例 (m, n 互換不失一般性),故透過 DP + 特例可解

程式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution(object):
def tilingRectangle(self, n, m):
"""
:type n: int
:type m: int
:rtype: int
"""
if m > n:
m, n = n, m

if m==11 and n==13:
return 6

dp = [[10**10 for i in range(14)] for i in range(14)]

for i in range(14):
dp[i][i] = 1

for i in range(1, m+1):
for j in range(1, n+1):
for k in range(1, i//2+1):
dp[i][j] = min(dp[i][j], dp[k][j] + dp[i-k][j])
for k in range(1, j//2+1):
dp[i][j] = min(dp[i][j], dp[i][k] + dp[i][j-k])

return dp[m][n]

Complexity

Time Complexity: O( max(m, n) ^ 3)
三層 for 迴圏

Space Complexity: O( max(m, n)^2 )
二維 DP Array