learn from ![this]()
class Solution {
public:
int numSquares(int n) {
if(n<=0)return 0;
int * dp = new int[n+1]();
for(int i=1;i<=n;i++){
dp[i]= INT_MAX;
for(int j =1;j*j <=i;j++){
int tmp = dp[i-j*j]+1;
dp[i]=dp[i]<tmp?dp[i]:tmp;
}
}
//for(int i=0;i<=n;i++)cout<< dp[i]<<' ';
return dp[n];
}
};
class Solution {
public:
int numSquares(int n) {
if (n <= 0)return 0;
else if(pow((int)sqrt(n),2) == n)return 1;
vector<int> perfectSquares;//candinates
vector<int> cntPerfectSquares(n);//count_index
for (int i = 1; i*i <= n; i++)
{
perfectSquares.push_back(i*i);
cntPerfectSquares[i*i - 1] = 1;
}
queue<int> searchQ;
for (auto& i : perfectSquares) searchQ.push(i);
int currCntPerfectSquares = 1;
while (!searchQ.empty())//BFS
{
currCntPerfectSquares++;
int searchQSize = searchQ.size();
for (int i = 0; i < searchQSize; i++)
{
int tmp = searchQ.front();
for (auto& j : perfectSquares)
{
if (tmp + j == n)return currCntPerfectSquares;
else if ((tmp + j < n) && (cntPerfectSquares[tmp + j - 1] == 0))
{
cntPerfectSquares[tmp + j - 1] = currCntPerfectSquares;
searchQ.push(tmp + j);
}
else if (tmp + j > n)break;
}
searchQ.pop();
}
}
return 0;
}
};