完全平方数

复习bfs

这题我们用bfs 做

class Solution {
public:
    int numSquares(int n) {
        queue <int> q;
        vector <int> dist(n+1,INT_MAX);
        q.push(0);
        dist[0] = 0;
        while(q.size())
        {
            int f = q.front();
            q.pop();
            if (f == n) return dist[f];
                for (int i = 1;i*i+f<=n;i++)
                {
                    int j = f + i*i;
                    if (dist[j] > dist[f] + 1 )
                    { 
                        dist[j] =  dist[f] + 1 ;
                        q.push(j);
                    }
                       
                }
        }
        return 0;
    }
};
原文地址:https://www.cnblogs.com/ranzhong/p/14145529.html