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

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, long long target) {
        vector<vector<int>> ans;
        const int N = nums.size();

        if (N < 4) return ans;

        sort(nums.begin(), nums.end());

        for (int i = 0; i < N - 3; ++i) {
            if (i > 0 && nums[i - 1] == nums[i]) continue;

            for (int j = i + 1; j < N - 2; ++j) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;

                long long complement = target - nums[i] - nums[j];
                if (nums[j + 1] > complement / 2) continue;
                vector<vector<int>> pairs = twoSum(nums, j + 1, complement);

                for (auto& pair : pairs) {
                    pair.push_back(nums[j]);
                    pair.push_back(nums[i]);
                    ans.push_back(pair);
                }
            }
        }
        return ans;
    }

    vector<vector<int>> twoSum(vector<int>& nums, int start, long long target) {
        unordered_set<long long> s;
        vector<vector<int>> res;
        
        for (int i = start; i < nums.size(); ++i) {
            if (res.empty() || res.back()[1] != nums[i]) {
                if (s.count(target - nums[i])) {
                    res.push_back({int(target - nums[i]), nums[i]});
                }
            }
            s.insert(nums[i]);
        }
        
        return res;
    }

};
206818