LeetCode: 279. Perfect Squares

题目描述

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:

1
2
3
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

1
2
3
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n+1);
int element = 1;
for (int i = 1; i <= n; i++) {
dp[i] = i;
if (pow(element+1, 2) <= i) {
element += 1;
}
for (int j = 1; j <= element; j++) {
dp[i] = min(dp[i], dp[i-pow(j, 2)] + 1);
}
}
return dp[n];
}
};