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
.
思路是酱紫滴:
dp[0] = 0
dp[1] = dp[0]+1 = 1
dp[2] = dp[1]+1 = 2
dp[3] = dp[2]+1 = 3
dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 }
= Min{ dp[3]+1, dp[0]+1 }
= 1
dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 }
= Min{ dp[4]+1, dp[1]+1 }
= 2
.
.
.
dp[13] = Min{ dp[13-1*1]+1, dp[13-2*2]+1, dp[13-3*3]+1 }
= Min{ dp[12]+1, dp[9]+1, dp[4]+1 }
= 2
.
.
.
dp[n] = Min{ dp[n - i*i] + 1 }, n - i*i >=0 && i >= 1
有的人认为,dp[ n ] = 1 + dp[ n - 离它最近的平方数 * 离它最近的平方数 ],这种想法是不对的,反例就是 n=12 时,结果是 3,因为 4+4+4=12,而不是 9+1+1+1 的 4。
代码如下:
public int numSquares(int n) {
int[] dp = new int[n + 1];
dp[0] = 0;
for(int i = 1; i <= n; ++i) {
int min = Integer.MAX_VALUE;
int square = 1;
while(i - square*square >= 0) {
min = Math.min(min, dp[i - square*square] + 1);
++square;
}
dp[i] = min;
}
return dp[n];
}
另外,还有大神用了神奇的数学方法:
4^k(8m+7) 法来自于 Lagrange's Four Square theorem 和 Legendre's three-square theorem.
-
基于 Lagrange's Four Square theorem, 只有 4 种可能的结果: 1, 2, 3, 4.
-
基于 Legendre's three-square theorem, 如果 n 能被写成 4^k(8m+7) 的形式,那么它不能被表示为 1个 或 2个 或 3个 整数的和。
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; // n = n/4
}
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;
}
};