标签: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; }
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