perfect squares
class Solution {
public:
int numSquares(int n) {
if(n <= 3) {
return n;
}
queue <pair<int, int>> q;
q.push(make_pair(n, 0));
int min = n;
while(!q.empty()) {
int nextNum = q.front().first;
int nextCnt = q.front().second;
q.pop();
int i = 1;
while(nextNum >= i*i) {
i += 1;
}
i -= 1;
nextCnt += 1;
for(;i>=1; i--) {
int temp = nextNum - (i * i);
if(temp == 0) {
if(min > nextCnt) {
min = nextCnt;
}
}
if(nextCnt < min) {
q.push(make_pair(temp, nextCnt));
}
}
}
return min;
}
};Last updated
Was this helpful?