题目如下:
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
andA2
differ if and only if there is some indexi
such 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 <= 12
0 <= A[i] <= 1e9
解题思路:因为A的长度最大才12,直接BFS计算就可以了。依次把[已经选好的数字中最后一个,可以选择的数字列表]加入队列即可。这里要注意去重,在可以选择的数字列表中可以存在重复,如果重复的数字恰好可以与已经选好的数字中最后一个的和可以开平方,那么重复的数字中只能选择一个加入队列。
代码如下:
class Solution(object): def numSquarefulPerms(self, A): """ :type A: List[int] :rtype: int """ import math def is_sqr(n): a = int(math.sqrt(n)) return a * a == n queue = [] for v in ((list(set(A)))): inx = A.index(v) queue.append((v,A[:inx] + A[inx+1:])) res = 0 while len(queue) > 0: last,choice = queue.pop(0) if len(choice) == 0: res += 1 for i,v in enumerate(list(set(choice))): if is_sqr(last+v): inx = choice.index(v) queue.append((v,choice[:inx] + choice[inx+1:])) return res