题目描述
动态规划
class Solution {
public int numSquares(int n) {
int[] dp = new int[n+1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0]=0;
int restrict = (int)Math.ceil(Math.sqrt(n));
int[] squrNum = new int[restrict+1];
for(int i=0;i<=restrict;i++){
squrNum[i] = i*i;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=restrict;j++){
if(squrNum[j]>i) break;
dp[i] = Math.min(dp[i],dp[i-squrNum[j]]+1);
}
}
return dp[n];
}
}
递归
class Solution {
public int numSquares(int n) {
int restrict = (int)Math.ceil(Math.sqrt(n));
Set<Integer> sqrts = new HashSet<>();
for(int i=0;i<=restrict;i++){
sqrts.add(i*i);
}
int count = 1;
for (; count <= n; ++count) {
if (getCount(n, count,sqrts))
return count;
}
return count;
}
public boolean getCount(int n,int count,Set<Integer> sqrts){
if(count==1) return sqrts.contains(n);
for(int num:sqrts){
if(getCount(n-num,count-1,sqrts)) return true;
}
return false;
}
}