LeetCode-数据结构-完全平方数

文章目录

完全平方数

给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

输入: n = 12

输出: 3

解释: 12 = 4 + 4 + 4.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-islands

广搜

这道题我将他抽象为从n开始,每次减少的距离为从1开始的平方数,我使用getsqu函数获取从1到(i*i<n)之间的平方数,相当于每一次的搜索是从n开始遍历getque里面的距离,若已visit过则跳过,重复操作直到队列头元素减去某一平方数的距离next==0为止,此时则找到乐所需;

class Solution {
public:
     vector<int> getsqu(int n) {
          vector<int> res;
          for(int i = 1; i*i <= n; i++) {
               res.push_back(i*i);
          }
          return res;
     }
     int numSquares(int n) {
          vector<int> squares = getsqu(n);
          vector<bool> visited(n);
          queue<int> q;
          q.push(n);
          visited[n] = true;
          int res = 0;
          while(!q.empty()) {
             int size = q.size();
             for(int i = 0; i < size; i++) {
                int cur = q.front();
                q.pop();
                for(int num: squares) {
                   int next = cur - num;
                   if(next < 0) break;
                   if(next == 0) return res;
                   if(visited[next]) continue;
                   visited[next] = true;
                   q.push(next);
                }
             }
           res++;
          }
          retuern n;
     }
     
     
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值