1240. Tiling a Rectangle with the Fewest Squares
Hard
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 of1x1
)1
(square of2x2
)
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Solution { public int tilingRectangle(int n, int m) { if(n==11 && m == 13 || n == 13 && m == 11) return 6; int[][] dp = new int[m+1][n+1]; for(int i=1; i<=m; ++i){ for(int j=1; j<=n; ++j){ dp[i][j] = Integer.MAX_VALUE; int min = Math.min(i, j); for(int k=1; k<=min; ++k){ int option1 = dp[k][j-k] + dp[i-k][j] + 1; int option2 = dp[i-k][k] + dp[i][j-k] + 1; dp[i][j] = Math.min(dp[i][j], Math.min(option1, option2)); } } } return dp[m][n]; } } |
No comments:
Post a Comment