279. Perfect Squares
problem description
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.algorithm thought
code
class Solution {
public:
int numSquares(int n) {
static vector<int> dp(1,0);
while(n>=dp.size()){
int t=INT_MAX;
for(int i=1;i*i<=dp.size();++i){
t=min(t,dp[dp.size()-i*i]+1);
}
dp.push_back(t);
}
return dp[n];
}
};algorithm analysis
Last updated