Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...
) which sum ton.
For example, given n = 12
, return 3
because 12 = 4 + 4 + 4
; given n = 13
, return 2
because 13 = 4 + 9
.
动态规划:
public class Solution {
public int numSquares(int n) {
if(n==0) return 0;
if(n==1) return 1;
int[] dp=new int[n+1];
dp[0]=0;dp[1]=1;
for(int i=2;i<=n;i++){
int k=(int) Math.sqrt(i);
dp[i]=i;
for(int j=k;j>=1;j--){
dp[i]=Math.min(dp[i],dp[i-j*j]+1);
}
}
return dp[dp.length-1];
}
}