z2529827226
class Solution
{
public:
    int numSquares(int n)
    {
        queue<pair<int, int> > pq; //队列中放置一组数据
        vector<bool> used(n + 1, false);
        pq.push(make_pair(n, 0));

        while (!pq.empty())
        {
            int num = pq.front().first;
            int step = pq.front().second;

            pq.pop();
            for (int i = 1; num - i * i >= 0; ++i)
            {
                int a = num - i * i;
               
                if (a == 0)
                {
                    return step + 1;   //一旦发现为空就立即返回,因为先为空的它的层数自然也最少
                }
                if (a > 0)
                {
                    if (!used[a])
                    {
                        pq.push(make_pair(a, step + 1));
                        used[a] = true;
                    }
                }
            }
        }
        return 0;
    }
};

 

分类:

技术点:

相关文章:

  • 2021-06-11
  • 2021-12-13
  • 2021-06-04
  • 2021-05-15
  • 2021-11-10
  • 2022-03-04
  • 2021-12-02
  • 2021-10-20
猜你喜欢
  • 2021-07-05
  • 2021-07-21
  • 2021-05-13
相关资源
相似解决方案