<p>An array is <strong>squareful</strong> if the sum of every pair of adjacent elements is a <strong>perfect square</strong>.</p>

<p>Given an integer array nums, return <em>the number of permutations of </em><code>nums</code><em> that are <strong>squareful</strong></em>.</p>

<p>Two permutations <code>perm1</code> and <code>perm2</code> are different if there is some index <code>i</code> such that <code>perm1[i] != perm2[i]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,17,8]
<strong>Output:</strong> 2
<strong>Explanation:</strong> [1,8,17] and [17,8,1] are the valid permutations.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [2,2,2]
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 12</code></li>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
</ul>

map <int,bool> mp;
int dp[1<<12][12][12];
int f(int i,int lst,int mask,vector<int>& a)
{
    int n=a.size();
    if (i==n) return 1;
    if (dp[mask][i][lst]!=-1) return dp[mask][i][lst];
    int ans=0;
    set <int> st;
    if (i==0){
        for (int j=0;j<n;j++){
            if (st.find(a[j])!=st.end()) continue;
            st.insert(a[j]);
            ans+=f(i+1,j,(1<<j),a);
        }
    }
    else{
        for (int j=0;j<n;j++){
            if (!(mask&(1<<j))){
                if (mp.count(a[j]+a[lst])){
                    if (st.find(a[j])!=st.end()) continue;
                    st.insert(a[j]);
                    ans+=f(i+1,j,mask|(1<<j),a);
                }
            }
        }
    }
    return dp[mask][i][lst]=ans;
}
class Solution {
public:
    int numSquarefulPerms(vector<int>& a) {
        int n=a.size();
        for (int i=0;i*i<=2e9;i++){
            mp[i*i]=true;
        }
        memset(dp,-1,sizeof(dp));
        return f(0,0,0,a);
    }
};
17900