<p>You are given an integer array <code>matchsticks</code> where <code>matchsticks[i]</code> is the length of the <code>i<sup>th</sup></code> matchstick. You want to use <strong>all the matchsticks</strong> to make one square. You <strong>should not break</strong> any stick, but you can link them up, and each matchstick must be used <strong>exactly one time</strong>.</p>

<p>Return <code>true</code> if you can make this square and <code>false</code> otherwise.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> matchsticks = [1,1,2,2,2]
<strong>Output:</strong> true
<strong>Explanation:</strong> You can form a square with length 2, one side of the square came two sticks with length 1.
</pre>

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

<pre>
<strong>Input:</strong> matchsticks = [3,3,3,3,4]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot find a way to form a square with all the matchsticks.
</pre>

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

<ul>
	<li><code>1 &lt;= matchsticks.length &lt;= 15</code></li>
	<li><code>1 &lt;= matchsticks[i] &lt;= 10<sup>8</sup></code></li>
</ul>

class Solution {
public:
    string getState(int s1,int s2,int s3,int s4){
        vector<int> arr = {s1,s2,s3,s4};
        sort(arr.begin(),arr.end());
        string state="";
        for(int i:arr){
            state+=to_string(i)+":";
        }
        return state;
    }
    bool dfs(int i,int s1,int s2,int s3,int s4,vector<int>& matchsticks,vector<map<string,bool>>& dp){
        if(i==matchsticks.size()) return s1==0 && s2==0 && s3==0 && s4==0;

        string state = getState(s1,s2,s3,s4);

        if(dp[i].find(state)!=dp[i].end()) return dp[i][state];

        bool ans = false;

        int v = matchsticks[i];
        if(s1-v>=0) ans = ans or dfs(i+1,s1-v,s2,s3,s4,matchsticks,dp);
        if(s2-v>=0) ans = ans or dfs(i+1,s1,s2-v,s3,s4,matchsticks,dp);
        if(s3-v>=0) ans = ans or dfs(i+1,s1,s2,s3-v,s4,matchsticks,dp);
        if(s4-v>=0) ans = ans or dfs(i+1,s1,s2,s3,s4-v,matchsticks,dp);



        return dp[i][state]=ans;
    }
    bool makesquare(vector<int>& matchsticks) {
        long long int s = 0;
        for(int i:matchsticks){
            s+=i;
        }
        if(s%4!=0) return false;
        sort(matchsticks.rbegin(),matchsticks.rend());
        vector<map<string,bool>> dp(matchsticks.size());
        return dfs(0,s/4,s/4,s/4,s/4,matchsticks,dp);      
    }
};
46141