279. Perfect Squares
# Medium
Optimize solution:
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