[leetcode]279. Perfect Squares
Analysis
missing—— [每天刷题并不难0.0]
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
Explanation:
Dynamic programing,res[i] represent the least number of perfect square numbers which sum to i. For each i<=n, it must be the sum of some number (i-jj) and a perfect square number (jj).
Implement
class Solution {
public:
int numSquares(int n) {
if(n <= 0)
return 0;
vector<int> res(n+1, INT_MAX);
res[0] = 0;
for(int i=1; i<=n; i++){
for(int j=1; j*j<=i; j++){
res[i] = min(res[i], res[i-j*j]+1);
}
}
return res.back();
}
};