Given an array
Aof 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
A1andA2differ if and only if there is some indexisuch thatA1[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 <= 120 <= A[i] <= 1e9
Approach #1: Math. [Java]
class Solution {
int ret = 0;
Map<Integer, Integer> cntMap = new HashMap<>();
Map<Integer, Set<Integer>> squareMap = new HashMap<>();
public int numSquarefulPerms(int[] A) {
for (int num : A) {
if (!cntMap.containsKey(num)) {
cntMap.put(num, 1);
squareMap.put(num, new HashSet<Integer>());
} else {
cntMap.put(num, cntMap.get(num) + 1);
}
}
for (int num1 : cntMap.keySet()) {
for (int num2 : cntMap.keySet()) {
double c = Math.sqrt(num1 + num2);
if (c == Math.floor(c)) {
squareMap.get(num1).add(num2);
squareMap.get(num2).add(num1);
}
}
}
for (int key : cntMap.keySet()) {
dfs(key, A.length - 1);
}
return ret;
}
public void dfs(int key, int left) {
cntMap.put(key, cntMap.get(key)-1);
if (left == 0) ret++;
else {
for (int next : squareMap.get(key)) {
if (cntMap.get(next) != 0) {
dfs(next, left - 1);
}
}
}
cntMap.put(key, cntMap.get(key)+1);
}
}
Reference:
https://leetcode.com/problems/number-of-squareful-arrays/discuss/238562/C%2B%2BPython-Backtracking