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.javaReturn the number of permutations of A that are squareful. Two permutations
A1
andA2
differ if and only if there is some indexi
such thatA1[i] != A2[i]
.spa
Example 1:code
Input: [1,17,8] Output: 2 Explanation: [1,8,17] and [17,8,1] are the valid permutations.
Example 2:blog
Input: [2,2,2] Output: 1
Note:element
1 <= A.length <= 12
0 <= A[i] <= 1e9
Approach #1: Math. [Java]leetcode
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:get
https://leetcode.com/problems/number-of-squareful-arrays/discuss/238562/C%2B%2BPython-Backtrackinginput