https://leetcode.com/problems/number-of-squareful-arrays/
https://leetcode.com/problems/number-of-squareful-arrays/discuss/238562/C%2B%2BPython-Backtracking
X. DP - Bit Masking
https://leetcode.com/problems/number-of-squareful-arrays/discuss/238871/Java-DP-7ms
DP Hamiltonian Path
X. Permutation
https://zxi.mytechroad.com/blog/searching/leetcode-996-number-of-squareful-arrays/
Time complexity: O(n!)
Space complexity: O(n)
https://leetcode.com/problems/number-of-squareful-arrays/discuss/238612/4msC%2B%2B-Simple-Backtracking-like-Permutations-II
Given an array
A
of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations
A1
and A2
differ if and only if there is some index i
such that A1[i] != A2[i]
.
Example 1:
Input: [1,17,8] Output: 2 Explanation: [1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2] Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
https://leetcode.com/problems/number-of-squareful-arrays/discuss/238562/C%2B%2BPython-Backtracking
- Count numbers ocuurrence.
- For each number
i
, find all possible next numberj
thati + j
is square. - Backtracking using dfs.
Time Complexity
It's
We can easily make case for N = 3 like [51,70,30].
It's
O(N^N)
if we have N different numbers and any pair sum is square.We can easily make case for N = 3 like [51,70,30].
Seems that no hard cases for this problem and int this way it reduces to O(N^2).
https://leetcode.com/articles/number-of-squareful-arrays/
Construct a graph where an edge from to exists if is a perfect square. Our goal is to investigate Hamiltonian paths of this graph: paths that visit all the nodes exactly once.
Let's keep a current
count
of what values of nodes are left to visit, and a count todo
of how many nodes left to visit.
From each node, we can explore all neighboring nodes (by value, which reduces the complexity blowup).
Time Complexity: , where is length of A
. A tighter bound is outside the scope of this article. However, it can be shown that the underlying graph is triangle free, as well as other properties that would dramatically shrink this complexity.
Map<Integer, Integer> count;
Map<Integer, List<Integer>> graph;
public int numSquarefulPerms(int[] A) {
int N = A.length;
count = new HashMap();
graph = new HashMap();
// count.get(v) : number of v's in A
for (int x : A)
count.put(x, count.getOrDefault(x, 0) + 1);
// graph.get(v) : values w in A for which v + w is a square
// (ie., "vw" is an edge)
for (int x : count.keySet())
graph.put(x, new ArrayList());
for (int x : count.keySet())
for (int y : count.keySet()) {
int r = (int) (Math.sqrt(x + y) + 0.5);
if (r * r == x + y)
graph.get(x).add(y);
}
// Add the number of paths that start at x, for all possible x
int ans = 0;
for (int x : count.keySet())
ans += dfs(x, N - 1);
return ans;
}
public int dfs(int x, int todo) {
count.put(x, count.get(x) - 1);
int ans = 1; // default if todo == 0
if (todo != 0) {
ans = 0;
for (int y : graph.get(x))
if (count.get(y) != 0) {
ans += dfs(y, todo - 1);
}
}
count.put(x, count.get(x) + 1);
return ans;
}
X. DP - Bit Masking
https://leetcode.com/problems/number-of-squareful-arrays/discuss/238871/Java-DP-7ms
public int numSquarefulPerms(int[] a) {
int n = a.length;
Arrays.sort(a);
boolean[][] s = new boolean[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
int sum = a[i] + a[j];
int sqrt = (int)(Math.sqrt(sum)+0.1);
s[i][j] = sqrt * sqrt == sum;
}
}
int ans = 0;
int[][] dp = new int[1<<n][n];
for(int i=0;i<n;){
dp[1<<i][i] = 1;
while(i+1 < n && a[i+1] == a[i]) i++;
i++;
}
for(int i=0;i<(1<<n);i++){
for(int j=0;j<n;j++){
if(dp[i][j] > 0){
for(int k=0;k<n;k++){
if((i&(1<<k))==0 && s[j][k]){
if(k==0 || a[k] != a[k-1] || (i&(1<<(k-1))) > 0){
dp[i|(1<<k)][k] += dp[i][j];
}
}
}
}
}
}
for(int i=0;i<n;i++) ans += dp[(1<<n)-1][i];
return ans;
}
dp[s][i] := # of ways to reach state s (binary mask of nodes visited) that ends with node i
dp[s | (1 << j)][j] += dp[s][i] if g[i][j]
Time complexity: O(n^2*2^n)
Space complexity: O(2^n)
Space complexity: O(2^n)
int numSquarefulPerms(vector<int>& A) {
const int n = A.size();
// For deduplication.
std::sort(begin(A), end(A));
// g[i][j] == 1 if A[i], A[j] are squareful.
vector<vector<int>> g(n, vector<int>(n));
// dp[s][i] := number of ways to reach state s and ends with node i.
vector<vector<int>> dp(1 << n, vector<int>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i == j) continue;
int r = sqrt(A[i] + A[j]);
if (r * r == A[i] + A[j])
g[i][j] = 1;
}
}
// For the same numbers, only the first one can be the starting point.
for (int i = 0; i < n; ++i)
if (i == 0 || A[i] != A[i - 1])
dp[(1 << i)][i] = 1;
int ans = 0;
for (int s = 0; s < (1 << n); ++s)
for (int i = 0; i < n; ++i) {
if (!dp[s][i]) continue;
for (int j = 0; j < n; ++j) {
if (!g[i][j]) continue;
if (s & (1 << j)) continue;
// Only the first one can be used as the dest.
if (j > 0 && !(s & (1 << (j - 1))) && A[j - 1] == A[j]) continue;
dp[s | (1 << j)][j] += dp[s][i];
}
}
for (int i = 0; i < n; ++i)
ans += dp[(1 << n) - 1][i];
return ans;
}
We construct the graph in the same method as in Approach 1.
Now, let
dfs(node, visited)
be the number of ways from node
to visit the remaining unvisited nodes. Here, visited
is a mask: (visited >> i) & 1
is true if and only if the i
th node has been visited.
Afterwards, we may have overcounted if there are repeated values in
A
. To account for this, for every x
in A
, if A
contains x
a total of k
times, we divide the answer by k!
.- Time Complexity: , where is length of
A
. - Space Complexity: .
int N;
Map<Integer, List<Integer>> graph;
Integer[][] memo;
public int numSquarefulPerms(int[] A) {
N = A.length;
graph = new HashMap();
memo = new Integer[N][1 << N];
for (int i = 0; i < N; ++i)
graph.put(i, new ArrayList());
for (int i = 0; i < N; ++i)
for (int j = i + 1; j < N; ++j) {
int r = (int) (Math.sqrt(A[i] + A[j]) + 0.5);
if (r * r == A[i] + A[j]) {
graph.get(i).add(j);
graph.get(j).add(i);
}
}
int[] factorial = new int[20];
factorial[0] = 1;
for (int i = 1; i < 20; ++i)
factorial[i] = i * factorial[i - 1];
int ans = 0;
for (int i = 0; i < N; ++i)
ans += dfs(i, 1 << i);
Map<Integer, Integer> count = new HashMap();
for (int x : A)
count.put(x, count.getOrDefault(x, 0) + 1);
for (int v : count.values())
ans /= factorial[v];
return ans;
}
public int dfs(int node, int visited) {
if (visited == (1 << N) - 1)
return 1;
if (memo[node][visited] != null)
return memo[node][visited];
int ans = 0;
for (int nei : graph.get(node))
if (((visited >> nei) & 1) == 0)
ans += dfs(nei, visited | (1 << nei));
memo[node][visited] = ans;
return ans;
}
X. Permutation
https://zxi.mytechroad.com/blog/searching/leetcode-996-number-of-squareful-arrays/
Time complexity: O(n!)
Space complexity: O(n)
https://leetcode.com/problems/number-of-squareful-arrays/discuss/238612/4msC%2B%2B-Simple-Backtracking-like-Permutations-II
The only difference is that by calling the recursion every time, the program would check whether the sum of the number on current index and the previous is a square number or not, to make sure the sub array from 0 to current index satisfys the Squareful definition.
int numSquarefulPerms(vector<int>& A) {
sort(A.begin(), A.end());
int ans = 0;
pmt(A, 0, ans);
return ans;
}
void pmt(vector<int> A, int idx, int& ans) {
if (idx >= A.size()) {
++ans;
}
for (int i = idx; i < A.size(); ++i) {
if (i > idx && A[i] == A[idx]) continue;
swap(A[i], A[idx]);
if ((idx == 0) || (idx > 0 && isSquare(A[idx] + A[idx - 1]))) {
pmt(A, idx + 1, ans);
}
}
}
bool isSquare(int v) {
int r = sqrt(v);
return r * r == v;
}
https://leetcode.com/problems/number-of-squareful-arrays/discuss/244838/Java3ms-Easy-Understand-Backtracking-Short-Solution public int numSquarefulPerms(int[] A) {
Arrays.sort(A);
return backtrack(0, new ArrayList<Integer>(), A, new boolean[A.length]);
}
private int backtrack(int res, List<Integer> tempList, int[] A, boolean[] used){
if(tempList.size() == A.length){
return ++res;
}else{
for(int i = 0; i < A.length; i++){
if(used[i]
|| i > 0 && A[i] == A[i-1] && !used[i - 1]
|| tempList.size() > 0 && !isSquareful(tempList.get(tempList.size() - 1) + A[i])) continue;
used[i] = true;
tempList.add(A[i]);
res = backtrack(res, tempList, A, used);
used[i] = false;
tempList.remove(tempList.size() - 1);
}
}
return res;
}
private boolean isSquareful(int x){
return (Double)Math.sqrt(x) == (int)Math.sqrt(x);
}