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
because12 = 4 + 4 + 4
; given n = 13
, return 2
because13 = 4 + 9
.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n+1,INT_MAX);
vector<int> num;
if(n<4) return n;
dp[1]=1;
int m=1;
for(int i=1;m<=n;)
{
if(m<0)
break;
dp[m]=1;
num.push_back(m);
i++;
m=i*i;
}
for(int i=1;i<=n;++i)
{
for(int j=0;j<num.size();++j)
if(dp[i]!=INT_MAX&&(i+num[j]<=n))
dp[i+num[j]]=min(dp[num[j]+i],1+dp[i]);
}
// cout<<dp[n];
return dp[n]==INT_MAX?n:dp[n];
}
};
优化后的做法,代码:
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n+1,INT_MAX);
for(int i=0,j=0;j<=n;j=i*i){
dp[j]=1;
++i;
}
for(int i=2;i<=n;++i){
if(dp[i]!=1){
for(int j=1,k=1;k<i;k=j*j){
dp[i]=min(dp[i],1+dp[i-k]);
j++;
}
}
}
return dp[n];
}
};