We are given an integer n, we have to determine the least no. of perfect squares which sum to n.
Example :
n = 12
and perfect squares up to n are 1, 4, 9, 16, 25... up to n
in this case these will be 1, 4, 9
so output will be 3 as 12 = 4 + 4 + 4
This is code in C++ which implements BFS.
int numSquares(int n) {
if(n < 0) return -1;
if(n == 1) return 1;
vector<int> perfectSqs;
queue<int> q;
int level = 0;
// for(int i=1; i*i<=n; i++) {
// perfectSqs.push_back(i*i);
// }
// for(int i=0; i<perfectSqs.size(); i++) {
// cout<<perfectSqs[i]<<' ';
// }
q.push(n);
while(!q.empty()) {
int size = q.size();
for(int i=0; i<size; i++) {
int curr = q.front();
q.pop();
if(curr == 0) return level;
for(int j=1; j*j<=curr; j++) {
int next = curr - j*j;
q.push(next);
}
}
level++;
}
return -1;
Everything else runs absolutely fine but time exceeds for input 7168
. 7167
also runs.
Can someone let me know where I am wrong?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…