279. Perfect Squares
# Medium
Optimize solution:
Initialize all squares'
count
with-1
.Initialize all known squares, like cheating table. If
count[x] = -1
, then number x is not a square.Only the number who is not a square is needed to compute.
If this number can be decomposeted into two squares, then
count[x] = 2
. Ohterwise continue computing usingDP
method.
class Solution {
public:
int numSquares(int n) {
int count[n+1]; // store count of each number from 1 to n
// initialize
for(int i = 1; i <= n; i ++) {
count[i] = -1;
}
for(int i = 0; i <= n; i ++) {
if(i*i <= n) {
count[i*i] = 1;
} else{
break;
}
}
// DP solve this
for(int x = 1; x <= n; x ++) {
if(count[x] == -1) {
count[x] = x;
// decomposite number x
for(int i = 1; i <= x/2; i ++) {
if(count[i] == 1 and count[x-i] == 1) {
count[x] = 2;
break;
} else if(count[i] != 1 and count[x-i] != 1) {
continue;
} else {
count[x] = min(count[i]+count[x-i] < count[x]);
}
}
}
}
return count[n];
}
};
Last updated
Was this helpful?