<p>You have a <code>grid</code> of size <code>n x 3</code> and you want to paint each cell of the grid with exactly one of the three colors: <strong>Red</strong>, <strong>Yellow,</strong> or <strong>Green</strong> while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).</p>

<p>Given <code>n</code> the number of rows of the grid, return <em>the number of ways</em> you can paint this <code>grid</code>. As the answer may grow large, the answer <strong>must be</strong> computed modulo <code>10<sup>9</sup> + 7</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/03/26/e1.png" style="width: 400px; height: 257px;" />
<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 12
<strong>Explanation:</strong> There are 12 possible way to paint the grid as shown.
</pre>

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

<pre>
<strong>Input:</strong> n = 5000
<strong>Output:</strong> 30228214
</pre>

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

<ul>
	<li><code>n == grid.length</code></li>
	<li><code>1 &lt;= n &lt;= 5000</code></li>
</ul>

class Solution {
    typedef long long ll;
    ll mod = 1e9+7;
    void generate_mask(int m,int msk,vector<int> &masks,int &pre_msk,int pre_col)
    {
        if(m==0)
        {
            masks.push_back(msk);
            return;
        }
        for(int i=1;i<=3;i++)
            if(pre_col!=i && ((pre_msk>>((m-1)*2))&3)!=i)
                generate_mask(m-1,msk|(i<<(m-1)*2),masks,pre_msk,i);
    }
    int func(int m,int&n,int idx,int msk,vector<vector<int>> &dp,unordered_map<int,vector<int>> &msk_map)
    {
        if(idx==n)
            return 1;
        if(dp[idx][msk]!=-1)
            return dp[idx][msk];
        if(msk_map.find(msk)==msk_map.end())
             generate_mask(m,0,msk_map[msk],msk,0);
        ll ans = 0;
        for(auto cur_msk : msk_map[msk])
        {
            ans += func(m,n,idx+1,cur_msk,dp,msk_map)*1LL;
            ans %= mod;
        }
        return dp[idx][msk] = ans;
    }
public:
    int numOfWays(int n)
    {
        vector<vector<int>> dp(n,vector<int>(1<<(2*3),-1));
        unordered_map<int,vector<int>> msk_map;
        return (int)func(3,n,0,0,dp,msk_map);
    }
};
32315