package com.app.main.LeetCode;
import java.util.Collection;
import java.util.Collections;
/**
*
* 1240
*
* hard
*
* https://leetcode.com/problems/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
*
*
* Created with IDEA
* author:Dingsheng Huang
* Date:2020/1/6
* Time:下午8:11
*/
public class TilingRectangleWithFewestSquares {
private int result = Integer.MAX_VALUE;
private int hMax;
public int tilingRectangle(int n, int m) {
if (n > m) {
return tilingRectangle(m, n);
}
int[] hArray = new int[n];
hMax = m;
dfs(hArray, 0);
return result;
}
private void dfs(int[] hAarray, int currRes) {
// pruning
if (currRes > result) {
return;
}
// search the h array , find the bottom
int bottom = 0;
for (int i = 1; i < hAarray.length; i++) {
if (hAarray[i] < hAarray[bottom]) {
bottom = i;
}
}
if (hAarray[bottom] == hMax) {
result = currRes;
return;
}
// find the right border
int temp = bottom;
while (temp <= hAarray.length - 1 && (temp - bottom + 1) <= hMax - hAarray[bottom] && hAarray[temp] == hAarray[bottom]) {
temp++;
}
temp--;
for (int i = 1; i <= temp - bottom + 1; i++) {
// update h array
for (int j = bottom; j < bottom + i; j++) {
hAarray[j] += i;
}
currRes++;
dfs(hAarray, currRes);
// backtrack
for (int j = bottom; j < bottom + i; j++) {
hAarray[j] -= i;
}
currRes--;
}
}
}
LeetCode--1240--hard--TilingRectangleWithFewestSquares
猜你喜欢
转载自blog.csdn.net/huangdingsheng/article/details/103979068
今日推荐
周排行