<p>Given a rectangle of size <code>n</code> x <code>m</code>, return <em>the minimum number of integer-sided squares that tile the rectangle</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/10/17/sample_11_1592.png" style="width: 154px; height: 106px;" /></p>

<pre>
<strong>Input:</strong> n = 2, m = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> <code>3</code> squares are necessary to cover the rectangle.
<code>2</code> (squares of <code>1x1</code>)
<code>1</code> (square of <code>2x2</code>)</pre>

<p><strong class="example">Example 2:</strong></p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/10/17/sample_22_1592.png" style="width: 224px; height: 126px;" /></p>

<pre>
<strong>Input:</strong> n = 5, m = 8
<strong>Output:</strong> 5
</pre>

<p><strong class="example">Example 3:</strong></p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/10/17/sample_33_1592.png" style="width: 224px; height: 189px;" /></p>

<pre>
<strong>Input:</strong> n = 11, m = 13
<strong>Output:</strong> 6
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n, m &lt;= 13</code></li>
</ul>

class Solution {
    int res;
    bool matrix[14][14];
    int n, m;
public:
    int tilingRectangle(int n, int m) {
        res = max(n, m);
        this->n = n;
        this->m = m;
        helper(0, 0, 0);
        return res;
    }

    void helper(int x, int y, int cnt){
        if(cnt>=res) return;

        if(x>=n){
            res = cnt;
            return;
        }

        if(y>=m){
            helper(x+1, 0, cnt);
            return;
        }

        if(matrix[x][y]){
            helper(x, y+1, cnt);
            return;
        }

        int len = min(n-x, m-y);
        while(len>0 && !valid(x, y, len)) len--;

        for(int k=len; k>=1; k--){
            fillup(x, y, k, true);
            helper(x, y+k, cnt+1);
            fillup(x, y, k, false);
        }
    }

    void fillup(int x, int y, int len, bool val){
        for(int i=x; i<x+len; i++){
            for(int j=y; j<y+len; j++){
                matrix[i][j] = val;
            }
        }
    }

    bool valid(int x, int y, int len){
        for(int i=x; i<x+len; i++){
            for(int j=y; j<y+len; j++){
                if(matrix[i][j]) return false;
            }
        }
        return true;
    }
};
7500