首页 > 其他 > 详细

完全平方数

时间:2020-03-22 16:07:55      阅读:65      评论:0      收藏:0      [点我收藏+]

给定正整数 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

完全平方数

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!