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.
n=a+b 所以 dp[n]=dp[a]+dp[b] 注意其中b可以取0,然后取最小就好。直观的解法
public class Solution {
public int numSquares(int n) {
if(n<1) return 0;
if(n==1) return 1;
int[] dp = new int[n+1];
for(int i=1; i*i <=n; i++){
dp[i*i] = 1;
}
for(int i=2; i < n+1; i++){
int t = Integer.MAX_VALUE;
for(int j=1; j <= i/2; j++){
t = Math.min(t, dp[j] + dp[i-j]);
}
dp[i] = dp[i]==1?1:t;
}
return dp[n];
}
}
但是这样的复杂度还是较高。
那么关键是减少对一些不好的情况的遍历,只需考虑加和中其中一个数为平方数即可。
改进后的代码
public class Solution {
public int numSquares(int n) {
if(n<1) return 0;
if(n==1) return 1;
int[] dp = new int[n+1];
for(int i=1; i*i <=n; i++){
dp[i*i] = 1;
}
for(int i=2; i < n+1; i++){
if(dp[i]==1) continue;
int t = Integer.MAX_VALUE;
for(int j=1; j*j < i; j++){
t = Math.min(t, dp[i-j*j] +1);
}
dp[i] = t;
}
return dp[n];
}
}