-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path279.perfect-squares.cc
More file actions
47 lines (42 loc) · 916 Bytes
/
279.perfect-squares.cc
File metadata and controls
47 lines (42 loc) · 916 Bytes
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
43
44
45
46
47
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <unordered_map>
// Runtime: 875 ms, faster than 11.22% of C++ online submissions for Perfect
// Squares. Memory Usage: 40.9 MB, less than 12.90% of C++ online submissions
// for Perfect Squares.
std::unordered_map<int, int> cache;
int numSquares(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
if (n < 0) {
return -1;
}
auto iter = cache.find(n);
if (iter != cache.end()) {
return iter->second;
}
int k = std::sqrt(n) + 1;
int min = -1;
for (auto i = k; i > 0; --i) {
int a = numSquares(n - i * i);
if (a == -1) {
continue;
}
if (min == -1 || (a + 1) < min) {
min = a + 1;
}
if (a == 0) {
break;
}
}
cache.insert(std::make_pair(n, min));
return min;
}
int main(int argc, char **argv) {
printf("ret = %d\n", numSquares(std::atoi(argv[1])));
}