<p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p>

<p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p>

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

<pre>
<strong>Input:</strong> n = 12
<strong>Output:</strong> 3
<strong>Explanation:</strong> 12 = 4 + 4 + 4.
</pre>

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

<pre>
<strong>Input:</strong> n = 13
<strong>Output:</strong> 2
<strong>Explanation:</strong> 13 = 4 + 9.
</pre>

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

<ul>
	<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
    int numSquares(int n) {
        // Consider a tree with root value 0 and children whose values are
        // perfect squares up to greatest_square. Each children also has
        // children with the same perfect squares as values. We perform a
        // BFS on this tree until we find a path whose nodes sum equals n.
        
        // The BFS queue will be used to store the square root of
        // each node, and the partial sum.
        queue<pair<int, int>> Q;
        
        Q.push({0, 0});
        int step = 0;
        while (!Q.empty()) {
            int size = Q.size();
            for (int i = 0; i < size; ++i) {
                pair<int, int>& pair = Q.front();
                int sqr_root    = pair.first;
                int partial_sum = pair.second;
                //int remain      = n - partial_sum;

                // We don't need to consider smaller squares since a path
                // with them will be considered in other tree branches.
                for (int r = sqr_root; r*r <= n - partial_sum; ++r) {
                    int square = r * r;
                    if (n - partial_sum == square) {
                        return step + 1;
                    }
                    Q.push({r, partial_sum + square});
                }

                Q.pop();
            }
            step++;
        }

        return -1;
    }
};
31646