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
.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
動態規劃法。初始化時令dp[i * i] = 1
,狀態轉移方程為dp[i + j * j] = min(dp[i] + 1, dp[i + j * j])
;
C++:
// Runtime: 544 ms
class Solution {
public:
int numSquares(int n) {
vector dp(n + 1, 0x7fffffff);
for (int i = 0; i * i <= n; i++)
{
dp[i * i] = 1;
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; i + j * j <= n; j++)
{
dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]);
}
}
return dp[n];
}
};
Java:
// Runtime: 69 ms
public class Solution {
public int numSquares(int n) {
int dp[] = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
for (int i = 1; i * i <= n; i++) {
dp[i * i] = 1;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; i + j * j <= n; j++) {
dp[i + j * j] = Math.min(dp[i] + 1, dp[i + j * j]);
}
}
return dp[n];
}
}