forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-squareful-arrays.cpp
48 lines (44 loc) · 1.22 KB
/
number-of-squareful-arrays.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
43
44
45
46
47
48
// Time: O(n!)
// Space: O(n^2)
class Solution {
public:
int numSquarefulPerms(vector<int>& A) {
unordered_map<int, int> count;
for (const auto& a : A) {
++count[a];
}
unordered_map<int, unordered_set<int>> candidate;
for (const auto& i : count) {
for (const auto& j : count) {
int x = i.first, y = j.first, s = sqrt(x + y);
if (s * s == x + y) {
candidate[x].emplace(y);
}
}
}
int result = 0;
for (const auto& i : count) {
dfs(candidate, i.first, A.size() - 1, &count, &result);
}
return result;
}
private:
void dfs(const unordered_map<int, unordered_set<int>>& candidate,
int x,
int left,
unordered_map<int, int> *count,
int *result) {
--(*count)[x];
if (!left) {
++(*result);
}
if (candidate.count(x)) {
for (const auto& y : candidate.at(x)) {
if ((*count)[y] > 0) {
dfs(candidate, y, left - 1, count, result);
}
}
}
++(*count)[x];
}
};