<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p>

<ul>
	<li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li>
	<li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li>
	<li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li>
</ul>

<p>You may return the answer in <strong>any order</strong>.</p>

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

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

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

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

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

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

/*
n1 + n2 + n3 + n4 = target <=>
-target + n1 + n2 + n3 = n4
*/

class Solution {
public:

    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        map<long, int> m1;
        for (auto& v : nums) {
            m1[v] = (m1.find(v) == m1.end()) ? 1 : m1[v]+1;
        }

        vector<long> nums2;
        for (auto&[k,v] : m1) {
            for (int i=min(4,v); i>0; i--) {
                nums2.push_back(k);
            }
        }

        sort(nums2.begin(), nums2.end());
        /*
        for (auto& v : nums2) {
            cout << v << ", ";
        }
        cout << endl;
        */

        set<vector<int>> s1;

        int z1 = nums2.size();
        for (int i1=0; i1<z1-3; i1++) {
            long n1 = nums2[i1];
            long t0 = target - n1;
            for (int i2=i1+1; i2<z1-2; i2++) {
                long n2 = nums2[i2];
                long t1 = t0 - n2;
                for (int i3=i2+1; i3<z1-1; i3++) {
                    long n3 = nums2[i3];
                    long t2 = t1 - n3;
                    vector<int> r2 = {(int)n1, (int)n2, (int)n3, (int) t2};
                    if (t2 < n3) continue;
                    if (m1.find(t2) == m1.end()) continue;
                    if (m1[t2] < count(r2.begin(), r2.end(), t2)) continue;
                    s1.insert(r2);
                }
            }
        }

        vector<vector<int>> r1(s1.begin(), s1.end());
        return r1;
    }
};

265593