Given a positive integer
n, find the least number of perfect square numbers (for example,
1, 4, 9, 16, ...
) which sum to
n.
For example, given n = 12
, return 3
because 12 = 4 + 4 + 4
; given n = 13
, return 2
because 13 = 4 + 9
.
跟求丑数类似,保存n之前的所有状态,DP。所有的数至少可以由1组成。
class Solution {
public:
int numSquares(int n) {
vector<int> squareNum(n+1, 0);
for (int i = 1; i <= n; ++i) {
squareNum[i] = i;
for (int j = 1; j * j <= i; ++j) {
squareNum[i] = min(squareNum[i], squareNum[i - j * j] + 1);
}
}
return squareNum[n];
}
};