题意: Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
思路:这题和之前322.Coins Change差不多,只是硬币变成了平方数,具体思路还是DP做,递推式都和之前那题一样:d[i]=min(d[i],d[i−c[i]]+1),每个数都由平方数组合而成,具体见代码:
class Solution {
public:
int numSquares(int n) {
vector<int> res(n+1,n+1);
res[0] = 0;
for (int i = 1;i<res.size();i++){
for(int j = 0;j<=int(sqrt(i));j++){
res[i] = min(res[i-j*j]+1,res[i]);
}
}
return res[n];
}
};
注意到其实在对应计算当前i时,之前的已经计算完了,有种递归的思路在里面,而且这题和322的题不同,它相当于隐含了每个数都有解的意思在里面。但是这个方法还有一个问题,就是问题题目判定程序都要重新构造一个长为n+1的数组,很费时间,所以Solutions里就有人写了下面这个新的方法:
class Solution
{
public:
int numSquares(int n)
{
if (n <= 0)
{
return 0;
}
// cntPerfectSquares[i] = the least number of perfect square numbers
// which sum to i. Since cntPerfectSquares is a static vector, if
// cntPerfectSquares.size() > n, we have already calculated the result
// during previous function calls and we can just return the result now.
static vector<int> cntPerfectSquares({0});
// While cntPerfectSquares.size() <= n, we need to incrementally
// calculate the next result until we get the result for n.
while (cntPerfectSquares.size() <= n)
{
int m = cntPerfectSquares.size();
int cntSquares = INT_MAX;
for (int i = 1; i*i <= m; i++)
{
cntSquares = min(cntSquares, cntPerfectSquares[m - i*i] + 1);
}
cntPerfectSquares.push_back(cntSquares);
}
return cntPerfectSquares[n];
}
};
这个静态方法中vector的声明只会被执行一次,所以之后小于上次执行函数中n的解,就可以直接从静态数组中读取出来了,当然这题还有一个数学的方法,也就是我之前说的这题必有解的原因,Lagrange’s four-square theorem,简单来说,就是一个自然数,必定能拆分成四个平方数(当然这里0也算平方数),所以只要求解出解是1~4之中哪个,再结合Legendre’s three-square theorem 就可以找出解是哪个了,具体看参考代码:
class Solution
{
private:
int is_square(int n)
{
int sqrt_n = (int)(sqrt(n));
return (sqrt_n*sqrt_n == n);
}
public:
// Based on Lagrange's Four Square theorem, there
// are only 4 possible results: 1, 2, 3, 4.
int numSquares(int n)
{
// If n is a perfect square, return 1.
if(is_square(n))
{
return 1;
}
// The result is 4 if and only if n can be written in the
// form of 4^k*(8*m + 7). Please refer to
// Legendre's three-square theorem.
while ((n & 3) == 0) // n%4 == 0
{
n >>= 2;
}
if ((n & 7) == 7) // n%8 == 7
{
return 4;
}
// Check whether 2 is the result.
int sqrt_n = (int)(sqrt(n));
for(int i = 1; i <= sqrt_n; i++)
{
if (is_square(n - i*i))
{
return 2;
}
}
return 3;
}
};
最后还有一个BFS的python的代码,比较有意思,也放上来
def numSquares(self, n):
if n < 2:
return n
lst = []
i = 1
while i * i <= n:
lst.append( i * i )
i += 1
cnt = 0
toCheck = {n}
while toCheck:
cnt += 1
temp = set()
for x in toCheck:
for y in lst:
if x == y:
return cnt
if x < y:
break
temp.add(x-y)
toCheck = temp
return cnt