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.
动态规划的状态及转移过程(关键步骤)如下:
解题代码
class Solution {
public:
int numSquares(int n) {
assert(n >= 1);
// memo[n] 表示以完全平方数分割n,最小的个数
vector<int> memo = vector<int>(n + 1, INT_MAX);
memo[0] = 0;
memo[1] = 1;
// 求解memo[i]
for (int i = 2; i <= n; i++){
for (int j = 1; j*j <= i; j++){
memo[i] = min(memo[i], 1 + memo[i - j*j]);
}
}
return memo[n];
}
};
结果
求 [ 2912 ] 的完美平方, 结果为 : 3
请按任意键继续. . .