zoukankan      html  css  js  c++  java
  • 【leetcode】996. Number of Squareful Arrays

    题目如下:

    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. 1 <= A.length <= 12
    2. 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
  • 相关阅读:
    samba 服务搭建
    lock
    dev GridControl FilterCriteria
    dev GridControl Column 背景色
    Microsoft NLayerApp案例理论与实践
    DDD
    .Net架构师-开闭原则
    .Net架构师-面向对象的设计原则
    .Net架构师-详解面向对象
    .Net架构师-面向过程和面向对象
  • 原文地址:https://www.cnblogs.com/seyjs/p/10447509.html
Copyright © 2011-2022 走看看