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 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 ;
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章