- 实际上就是0-1背包问题的变种
- 给正数n, 找到最少的平方数是的他们的和等于n
- 12, 返回3,因为12 = 4 + 4 + 4;
- 13, 返回2,因为13 = 4 + 9.
class Solution {
public:
int numSquares(int n) {
int dp[n+1];
for(int i = 0; i <= n; ++i){
dp[i] = i;
}
for(int i = 4; i <= n; ++i){
for(int j = 1; j <= sqrt(i); ++j){
if(j*j == i){
dp[i] = 1;
break;
}else
dp[i] = min(dp[i], 1 + dp[i - j*j]);
}
}
return dp[n];
}
};