LeetCode996.Number of Sequareful Arrays(正方形数组的数目)

996.Number of Sequareful Arrays(正方形数组的数目)

Description

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].


给定一个非负整数数组 A,如果该数组每对相邻元素之和是一个完全平方数,则称这一数组为正方形数组。

返回 A 的正方形排列的数目。两个排列 A1A2 不同的充要条件是存在某个索引 i,使得 A1[i] != A2[i]

题目链接:https://leetcode.com/problems/number-of-squareful-arrays/
个人网站:http://redtongue.cn or http://redtongue.github.io/

Difficulty: hard

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

参考代码

class Solution(object):
def numSquarefulPerms(self, A):
    N = len(A)
    count = collections.Counter(A)
    graph = {x: [] for x in count}
    for x in count:
        for y in count:
            if int((x+y)**.5 + 0.5) ** 2 == x+y:
                graph[x].append(y)
                
    def dfs(x, todo):
        count[x] -= 1
        if todo == 0:
            ans = 1
        else:
            ans = 0
            for y in graph[x]:
                if count[y]:
                    ans += dfs(y, todo - 1)
        count[x] += 1
        return ans
        
    return sum(dfs(x, len(A) - 1) for x in count)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值