c++
class Solution {
public:
int numSquares(int n) {
if (n < 1) return 0;
vector<int> cache(n+1, INT_MAX);
cache[1] = 1;
for (int i = 2; i <= n; ++i) {
for (int j = 1; j*j <= i; ++j) {
if (j*j == i) {
cache[i] = 1;
break;
}
cache[i] = min(cache[i], cache[i - j*j] + 1);
}
}
return cache[n];
}
};