Number of Squareful Arrays
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.Input: [2,2,2]
Output: 1Basic Idea:
Solution 1: DFS + Pruning
Last updated
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.Input: [2,2,2]
Output: 1Last updated
class Solution {
public int numSquarefulPerms(int[] A) {
return dfs(A, 0);
}
private int dfs(int[] A, int pos) {
if (pos == A.length) {
return 1;
}
int ret = 0;
// 用于去重,不用重复数字替换pos
Set<Integer> used = new HashSet<>();
for (int i = pos; i < A.length; ++i) {
if (!used.add(A[i]) && i > pos) continue;
if (pos > 0 && !isValid(A[i], A[pos - 1])) continue; // pruning
swap(A, pos, i);
ret += dfs(A, pos + 1);
swap(A, pos, i);
}
return ret;
}
private void swap(int[] A, int i, int j) {
int t = A[i];
A[i] = A[j];
A[j] = t;
}
private boolean isValid(int a, int b) {
int sum = a + b;
return (int)Math.pow((int)Math.sqrt(sum), 2) == sum;
}
}