class Solution {
public:
int numSquares(int n) {
vector<int> dp(n + 1);
//对每一个进行计算可以由多少个完全平方数组成
for(int i = 1; i <= n; ++i){
int minN = INT_MAX;
//i 肯定可以由 (i - j * j) + j * j组成
//那么逐个比较需要的完全平方数的数量,取小
//同理n也可以得出
for(int j = 1; j * j <= i; ++j){
minN = min(minN, dp[i - j * j]);
}
dp[i] = minN + 1;
}
return dp[n];
}
};
Accepted
588/588 cases passed (96 ms)
Your runtime beats 66.1 % of cpp submissions
Your memory usage beats 51.97 % of cpp submissions (8.9 MB)