一、题目说明
题目279. Perfect Squares,给定一个正整数n,找到m个数其平方和刚好是n。求m的最小值,难度是Medium!
二、我的解答
bfs算法:
class Solution{
public:
//bfs
int numSquares(int n){
queue<int> q;
q.push(n);
int sum=0;
while(1){
int l=q.size();
for(int i=0;i<l;i++){
int f=q.front();
if(f==0) return sum;
for(int i=1;i*i<=f;i++) {
if(f-i*i==0) return sum+1;
q.push(f-i*i);
};
q.pop();
}
sum++;
}
}
};
性能如下:
Runtime: 132 ms, faster than 42.52% of C++ online submissions for Perfect Squares.
Memory Usage: 53.2 MB, less than 5.77% of C++ online submissions for Perfect Squares.
优化:
class Solution{
public:
//bfs
int numSquares(int n){
queue<int> q;
q.push(n);
int level = 0;
vector<bool> visit(n + 1, false);
while(!q.empty())
{
int size = q.size();
level++;
for(int i = 0; i < size; i++)
{
int temp = q.front();
q.pop();
visit[temp] = true;
for(int i = 1; i * i <= temp; i++)
{
if(temp == i * i) return level;
if(!visit[temp - i * i]) q.push(temp - i * i);
}
}
}
return level;
}
};
Runtime: 124 ms, faster than 46.86% of C++ online submissions for Perfect Squares.
Memory Usage: 29.7 MB, less than 11.54% of C++ online submissions for Perfect Squares.
三、优化措施
dp:
class Solution{
public:
int numSquares(int n){
vector<int> dp(n+1);
for(int i=1;i<=n;i++){
dp[i] = i;
}
for(int i=2;i<=n;i++){
for(int j=1;j*j<=i;j++){
dp[i] = min(dp[i],dp[i-j*j]+1);
}
}
return dp[n];
}
};
性能如下:
Runtime: 108 ms, faster than 58.71% of C++ online submissions for Perfect Squares.
Memory Usage: 11.4 MB, less than 61.54% of C++ online submissions for Perfect Squares.