279. Perfect Squares
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
广度优先搜索法
class Solution {
public:
int numSquares(int n) {
queue<int> q;
int steps = 0;
q.push(n);
vector<bool> booked(n+1,false);
booked[n]=true;
while(!q.empty())
{
for(int i=q.size();i>0;i--)
{
int ans = q.front();
q.pop();
for(int i=1;i<=sqrt(n);i++)
{
int ant = ans-i*i;
if(ant<0) break;
if(ant == 0) return steps+1;
if(booked[ant]== false)
{
booked[ant]=true;
q.push(ant);
}
}
}
steps++;
}
return 0;
}
};
四平方和定理
四平方和定理说明每个正整数均可表示为4个整数的平方和。它是费马多边形数定理和华林问题的特例。注意有些整数不可表示为3个整数的平方和,例如7。
static int x = [](){
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
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) {
return (a!=0) + (b!=0);
}
}
return 3;
}
};