https://leetcode-cn.com/problems/perfect-squares/
給定正整數(shù) n,找到若干個完全平方數(shù)(比如 1, 4, 9, 16, ...)使得它們的和等于 n。你需要讓組成和的完全平方數(shù)的個數(shù)最少。
我一開始想的是動態(tài)規(guī)劃
自己沒有寫就搬運了別人的
但dp的時間復雜度硬傷
class Solution {
public:
int numSquares(int n) {
vector<int> det(n+1, INT_MAX);
det[0] = 0;
for(int i = 1; i <= n; i++){
int temp = sqrt(i);
if(temp * temp == i) det[i] = 1;
else{
for(int j = 1; j <= temp; j++)
det[i] = min(det[i], 1 + det[i-j*j]);
}
}
return det[n];
}
};
居居的方法:廣搜
居居:“dp的時間復雜度太高了?!?br> but事實是用時上廣搜也沒好到哪里去并且debug用了相當久……
class Solution {
public:
struct node{
int x,f;
};
queue<node> q;
int numSquares(int n) {
int vis[1000005]={0};
node a,p;
a.x=n;
a.f=0;
q.push(a);
vis[n]=1;
while(!q.empty()){
a=q.front();
q.pop();
for(int i=1;i*i<=n;i++){
int t=a.x-i*i;
if(t==0)return a.f+1;
if(t>0&&!vis[t]){
p.x=t;
p.f=a.f+1;
vis[t]=1;
q.push(p);
}
}
}
return 0;
}
};
最后發(fā)現(xiàn)這是個數(shù)學問題……
四平方定理: 任何一個正整數(shù)都可以表示成不超過四個整數(shù)的平方之和。
推論:滿足四數(shù)平方和定理的數(shù)n(四個整數(shù)的情況),必定滿足 n=4^a(8b+7)
看到的證明清晰且有拓展的網(wǎng)站:https://www.changhai.org/articles/science/mathematics/four_square_theorem.php
class Solution {
public:
int numSquares(int n) {
while(n%4==0)n/=4;
if(n%8==7)return 4;
for(int a=0;a*a<=n;a++) {
int b=sqrt(n-a*a);
if(a*a+b*b==n){
if(!a||!b)
return 1;
return 2;
}
}
return 3;
}
};