代码拉取完成,页面将自动刷新
// 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];
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。