这个题和coin change一样的。。
class Solution {
public int numSquares(int n) {
int[] num = new int[n + 1];
int index = 0;
for(int i = 1; i * i <= n; i++) {
num[index++] = i*i;
}
int[] res = new int[n + 1];
res[0] = 0;
for (int i = 1; i <= n; i++) {
res[i] = n + 1;
}
for(int i = 0; i < index; i++) {
for (int j = 0; j <= n; j++) {
if (j >= num[i]){
res[j] = Math.min(res[j], res[j-num[i]] + 1);
}
}
}
if (res[n] == (n + 1)){
return -1;
}
return res[n];
}
}