Perfect Squares
Desicription
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
Example 1:
代码语言:javascript复制Input: n = 12
Output: 3
Explanation: 12 = 4 4 4.
Example 2:
代码语言:javascript复制Input: n = 13
Output: 2
Explanation: 13 = 4 9.
Solution
代码语言:javascript复制class Solution {
public:
int numSquares(int n) {
vector<int> dp(n 1, INT_MAX);
dp[0] = 0;
for(int i = 1, squares; (squares = i * i) <= n; i ) {
for(int j = squares; j <= n; j ) {
if(dp[j] > dp[j - squares] 1) {
dp[j] = dp[j - squares] 1;
}
}
}
return dp[n];
}
};