-
Notifications
You must be signed in to change notification settings - Fork 259
/
Copy pathperfect-squares.cpp
42 lines (39 loc) · 981 Bytes
/
perfect-squares.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Time: O(n * sqrt(n))
// Space: O(n)
class Solution {
public:
/**
* @param n a positive integer
* @return an integer
*/
int numSquares(int n) {
static vector<int> num{0};
while (num.size() <= n) {
int squares = numeric_limits<int>::max();
for (int i = 1; i * i <= num.size(); ++i) {
squares = min(squares, num[num.size() - i * i] + 1);
}
num.emplace_back(squares);
}
return num[n];
}
};
// Time: O(n * sqrt(n))
// Space: O(n)
class Solution2 {
public:
/**
* @param n a positive integer
* @return an integer
*/
int numSquares(int n) {
vector<int> num(n + 1, numeric_limits<int>::max());
num[0] = 0;
for (int i = 0; i <= n; ++i) {
for (int j = i - 1, k = 1; j >= 0; ++k, j = i - k * k) {
num[i] = min(num[i], num[j] + 1);
}
}
return num[n];
}
};