Problem
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example
Given n = 12, return 3 because 12 = 4 + 4 + 4
Given n = 13, return 2 because 13 = 4 + 9
Note
这道题在OJ有很多解法,公式法,递归法,动规法,其中公式法时间复杂度最优(four square theorem
)。
不过我觉得考点还是在动规吧,也更好理解。
Solution
1. 动态规划法
public class Solution {
public int numSquares(int n) {
//建立空数组dp:从0到n每个数包含最少平方数情况,先fill所有值为Integer.MAX_VALUE;
int[] dp = new int[n+1];
Arrays.fill(dp, Integer.MAX_VALUE);
//将0到n范围内所有平方数的dp值赋1;
for (int i = 0; i*i <= n; i++) {
dp[i*i] = 1;
}
//两次循环更新dp[i+j*j],当它本身为平方数时,dp[i+j*j] < dp[i]+1
for (int i = 0; i <= n; i++) {
for (int j = 0; i+j*j <= n; j++) {
dp[i+j*j] = Math.min(dp[i]+1, dp[i+j*j]);
}
}
return dp[n];
}
}
2. 简化动态规划法
public class Solution {
public int numSquares(int n) {
int[] dp = new int[n+1];
for (int i = 0; i <= n; i++) {
dp[i] = i;
for (int j = 0; j*j <= i; j++) {
dp[i] = Math.min(dp[i], dp[i-j*j]+1);
}
}
return dp[n];
}
}
3. 四平方和定理法
public class Solution {
public int numSquares (int n) {
int m = n;
while (m % 4 == 0)
m = m >> 2;
if (m % 8 == 7)
return 4;
int sqrtOfn = (int) Math.sqrt(n);
if (sqrtOfn * sqrtOfn == n) //Is it a Perfect square?
return 1;
else {
for (int i = 1; i <= sqrtOfn; ++i){
int remainder = n - i*i;
int sqrtOfNum = (int) Math.sqrt(remainder);
if (sqrtOfNum * sqrtOfNum == remainder)
return 2;
}
}
return 3;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。