<p>Suppose you have <code>n</code> integers labeled <code>1</code> through <code>n</code>. A permutation of those <code>n</code> integers <code>perm</code> (<strong>1-indexed</strong>) is considered a <strong>beautiful arrangement</strong> if for every <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>either</strong> of the following is true:</p>

<ul>
	<li><code>perm[i]</code> is divisible by <code>i</code>.</li>
	<li><code>i</code> is divisible by <code>perm[i]</code>.</li>
</ul>

<p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of the <strong>beautiful arrangements</strong> that you can construct</em>.</p>

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

<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> 2
<b>Explanation:</b> 
The first beautiful arrangement is [1,2]:
    - perm[1] = 1 is divisible by i = 1
    - perm[2] = 2 is divisible by i = 2
The second beautiful arrangement is [2,1]:
    - perm[1] = 2 is divisible by i = 1
    - i = 2 is divisible by perm[2] = 1
</pre>

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

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>

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

<ul>
	<li><code>1 &lt;= n &lt;= 15</code></li>
</ul>

class Solution {
public:
    int goFind(int num, int mask, int &n, unordered_map<int, vector<int>> &mp, vector<vector<int>> &dp) {
        if(num==0) {
            return 1;
        }
        if(dp[num][mask] != -1) {
            return dp[num][mask];
        }

        int cnt = 0;
        for(auto &it: mp[num]) {
            if(((mask>>it)&1) == 0) {
                cnt += goFind(num-1, ((mask) | (1<<it)), n, mp, dp);
            }
        }
        return dp[num][mask] = cnt;
    }
    int countArrangement(int n) {
        unordered_map<int, vector<int>> mp;
        for(int i=1;i<=n;i++) {
            for(int j=1;j<=n;j++) {
                if(i%j == 0 || j%i == 0) {
                    mp[i].push_back(j);
                }
            }
            // for(auto &it: mp[i]) {
            //     cout<<it<<" ";
            // }
            // cout<<(1<<15)<<"\n";
        }
        vector<vector<int>> dp(n+1, vector<int>((1<<16)+2, -1));
        return goFind(n, 0, n, mp, dp);
    }
};
45522