完全平方数

复习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;
    }
};

 

posted @ 2020-12-16 18:51  然终酒肆  阅读(71)  评论(0编辑  收藏  举报