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

#include <bits/stdc++.h>
#define ss second
#define ff first
#define pii pair<int,int>
#define pb push_back
#define ll long long
#define vi vector<int>
#define vvi vector<vi>
#define vll vector<ll>	
#define pll pair<ll,ll>
#define vpll vector<pll>
#define vvll vector<vll>
#define ld long double
#define um unordered_map
#define all(x) x.begin(),x.end()

class Solution {
public:
    ll n;

    struct h_{
        size_t operator()(const pll& key) const {
            ll h1=hash<ll>()(key.ff);
            ll h2= hash<ll>()(key.ss);

            return h1 ^ (h2<<1);
        }
    };
    unordered_map<pll,ll,h_> memo;
    ll foo(ll pos, ll mask){
        if(pos>n)return 1;

        if(memo.count({pos,mask}))return memo[{pos,mask}];

        ll res=0;
        for(ll bit = 0;bit<16;bit++){
            if(mask & (1<<bit)){
                ll set_ele = bit+1;
                if(set_ele<=n && (pos%set_ele==0  || set_ele%pos==0))res+=foo(pos+1,mask^(1<<bit));
            }
        }
        return  memo[{pos,mask}] = res; 
    }
    int countArrangement(int n_) {
        n=n_;

        ll mask=(1<<17)-1;
        return foo(1,mask); 
    }
};
14457