码迷,mamicode.com
首页 > 其他好文 > 详细

完全平方数

时间:2020-03-22 16:04:47      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:queue   col   idt   编译   pac   cli   pop   ack   end   

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

https://leetcode-cn.com/explore/learn/card/queue-stack/217/queue-and-bfs/874/

 

技术图片

 

 



1、c++

技术图片
#include "iostream"
#include <queue>
#include <unordered_set>
using namespace std;

class Solution{
        public:
                Solution() {};
                int numSquare(int n){
                        queue<int> q;
                        q.push(n);

                        unordered_set<int> sset;
                        sset.insert(n);
                        int count = 0;
                        while(!q.empty()){
                                cout<<"count:"<<count<<endl;
                                cout<<"q.size():"<<q.size()<<endl;
                                int s = q.size();
                                for(int i = 0; i< s; i++){
                                        int tmp = q.front();
                                        cout<<tmp<<endl;
                                        q.pop();
                                        for(int j = 1; j*j <= tmp; j++){
                                                int sub = tmp - j*j;
                                                cout<<"sub:"<<sub<<"  "<<endl;
                                                if(sub == 0) return count+1;
                                                if(sset.find(sub) == sset.end()){
                                                        sset.insert(sub);
                                                        q.push(sub);
                                                }
                                        }
                                }
                                count++;
                        }
                        return count;
                }
};

int main(){
        Solution solu;
        cout<<solu.numSquare(12)<<endl;
}
View Code

2、c++11编译

g++ -std=c++11 a.cpp

 

3、方法二:拉格朗日四平方和定理

https://zhuanlan.zhihu.com/p/104030654

完全平方数

标签:queue   col   idt   编译   pac   cli   pop   ack   end   

原文地址:https://www.cnblogs.com/bailuoxi/p/12546173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!