forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
92 lines (70 loc) · 2.06 KB
/
main3.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/// Source : https://leetcode.com/problems/number-of-squareful-arrays/
/// Author : liuyubobobo
/// Time : 2019-02-19
#include <iostream>
#include <vector>
#include <cmath>
#include <unordered_map>
using namespace std;
/// Memory Search
/// Divide corresponding factorial number to avoid repeating counting :-)
/// Time Complexity: O(n*2^n)
/// Space Complexity: O(n*2^n)
class Solution {
private:
int n;
public:
int numSquarefulPerms(vector<int>& A) {
n = A.size();
vector<vector<int>> g(n);
for(int i = 0; i < n; i ++)
for(int j = i + 1; j < n; j ++)
if(perfectSquare(A[i] + A[j])){
g[i].push_back(j);
g[j].push_back(i);
}
int res = 0;
vector<vector<int>> dp(n, vector<int>(1 << n, -1));
for(int i = 0; i < n; i ++)
res += dfs(g, i, 1 << i, dp);
unordered_map<int, int> freq;
for(int e: A) freq[e] ++;
for(const pair<int, int>& p: freq) res /= fac(p.second);
return res;
}
private:
int dfs(const vector<vector<int>>& g,
int index, int visited, vector<vector<int>>& dp){
if(visited == (1 << n) - 1)
return 1;
if(dp[index][visited] != -1) return dp[index][visited];
int res = 0;
for(int next: g[index])
if(!(visited & (1 << next))){
visited += (1 << next);
res += dfs(g, next, visited, dp);
visited -= (1 << next);
}
return dp[index][visited] = res;
}
int fac(int x){
if(x == 0 || x == 1) return 1;
return x * fac(x - 1);
}
bool perfectSquare(int x){
int t = sqrt(x);
return t * t == x;
}
};
int main() {
vector<int> A1 = {1, 17, 8};
cout << Solution().numSquarefulPerms(A1) << endl;
// 2
vector<int> A2 = {2, 2, 2};
cout << Solution().numSquarefulPerms(A2) << endl;
// 1
vector<int> A3(12, 0);
cout << Solution().numSquarefulPerms(A3) << endl;
// 1
return 0;
}