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
Solution
DFS + 剪枝去重
class Solution {
public:
bool isSquare(int a, int b) {
int s = sqrt(a + b);
return (a + b == s * s);
}
void dfs(const vector<int>& A, vector<int>& used, vector<int>& cur, int& num) {
if (cur.size() == A.size()) {
num++;
return;
}
for (int i = 0; i < A.size(); i++) {
if (used[i]) continue;
if (i > 0 && used[i - 1] && A[i] == A[i - 1]) continue;
if (!cur.empty() && !isSquare(A[i], cur.back())) continue;
cur.push_back(A[i]);
used[i] = 1;
dfs(A, used, cur, num);
used[i] = 0;
cur.pop_back();
}
}
int numSquarefulPerms(vector<int>& A) {
sort(begin(A), end(A));
vector<int> used(A.size());
vector<int> cur;
int num = 0;
dfs(A, used, cur, num);
return num;
}
};
注意,那三个continue
的顺序,剪枝的优先级不能弄混,否则效率差距蛮大。