Given a positive integern, find the least number of perfect square numbers (for example,1, 4, 9, 16, ...) which sum ton. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanat
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:
Input: n =
12
Output: 3
Explanation:
12 = 4 + 4 + 4.
Example 2:
Input: n =
13
Output: 2
Explanation:
13 = 4 + 9.
题解:
dp问题,每次更新加入新元素后每个数需要的最小个数。
class Solution {
public:
int numSquares(int n) {
int k = sqrt(n);
vector<int> dp;
for (int i = 0; i <= n; i++) {
dp.push_back(i);
}
for (int i = 1; i <= k; i++) {
for (int j = i * i; j <= n; j++) {
dp[j] = min(dp[j], 1 + dp[j - i * i]);
}
}
return dp[n];
}
};