题目描述
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.
分析
动态规划,求解最优化问题,自底向上。
代码
public int numSquares(int n) {
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
// 将所有平方数置1
for (int i = 0; i * i <= n; i++) {
dp[i * i] = 1;
}
for (int a = 1; a <= n; a++) {
for (int b = 1; a + b * b <= n; b++) {
// 取较小值,a + b * b也可能是平方数
dp[a + b * b] = Math.min(dp[a] + 1, dp[a + b * b]);
}
}
return dp[n];
}