leetcode 996. Number of Squareful Arrays

给定一个非负整数数组,如果任意相邻元素之和是一个完全平方数,则称该数组为完美平方数组。求满足条件的数组排列的数目。题目难点在于如何避免在同一条路径上选择相同的数。
摘要由CSDN通过智能技术生成

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 A1and 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

解题思路:

这道题思路的难点在于如何去重,就是某条路径上的同一层不能选同一个数;

if(i > 0 && !visited[i - 1] && A[i] == A[i - 1]) continue ;

class Solution {
public:
    int numSquarefulPerms(vector<int>& A) 
    {
        vector<int> cur , visited(A.size() , 0) ;
        sort(A.begin() , A.end()) ;
        dfs(A , visited , cur) ;
        return res ;
    }
    
    bool squareful(int x , int y)
    {
        int s = sqrt(x + y) ;
        return s * s == x + y ;
    }
    
    void dfs(vector<int>& A , vector<int> visited , vector<int> cur)
    {
        if(cur.size() == A.size())
        {
            res++;
            return ;
        }
        
        for(int i = 0 ; i < A.size() ; ++i)
        {
            if(visited[i]) continue ;
            if(i > 0 && !visited[i - 1] && A[i] == A[i - 1]) continue ;
            if(!cur.empty() && !squareful(A[cur.back()] , A[i])) continue ;
            
            visited[i] = 1 ;
            cur.push_back(i) ;
            dfs(A , visited , cur) ;
            visited[i] = 0 ;
            cur.pop_back() ;
        }
    }
    
private :
    
    int res = 0 ;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值