//给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。 
//
// 给你一个整数 n ,返回和为 n 的完全平方数的 最少数量 。 
//
// 完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。
// 
//
// 
//
// 示例 1: 
//
// 
//输入:n = 12
//输出:3 
//解释:12 = 4 + 4 + 4 
//
// 示例 2: 
//
// 
//输入:n = 13
//输出:2
//解释:13 = 4 + 9 
// 
//
// 提示: 
//
// 
// 1 <= n <= 104 
// 
// Related Topics 广度优先搜索 数学 动态规划 
// 👍 793 👎 0

/*
* 279 完全平方数
* 2021-03-12 15:54:53
* @author oxygenbytes
*/ 
#include "leetcode.h" 
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
    /*本质上就是宽搜求最短路径
     * 0->1
     *      -> 1
     *      -> 4
     *      -> 9
     *      -> 16
     *  ->4
     *      -> 1
     *      -> 4
     *      -> 9
     *      -> 16
     *  ->9
     *      -> 1
     *      -> 4
     *      -> 9
     *      -> 16
     *  ->16
     *      -> 1
     *      -> 4
     *      -> 9
     *      -> 16
     */
    int numSquares(int n) {
        queue<int> q;
        vector<int> dist(n+1, INT_MAX);
        q.push(0);
        // 从0到n的最短距离
        dist[0] = 0;
        while(q.size()){
            auto t = q.front();
            q.pop();
            if(t == n) return dist[t];
            for(int i = 1;i * i + t <= n;i++){
                int j = t + i * i;
                if(dist[j] > dist[t] + 1){
                    dist[j] = dist[t] + 1;
                    q.push(j);
                }
            }
        }
        return 0;
    }
};
//leetcode submit region end(Prohibit modification and deletion)