# 18. 4Sum 四数之和

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

``````For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1,  0, 0, 1],
[-2, -1, 1, 2],
[-2,  0, 0, 2]
]
``````

Difficulty: Medium

``````class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
set<vector<int>> res;
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i = 0; i < n-3; i++)
{
for (int j = i + 1; j < n-2;j++)
{
int left = j+1,right = n-1;
while (left <right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum==target)
{
vector<int> out;
out.push_back(nums[i]);
out.push_back(nums[j]);
out.push_back(nums[left]);
out.push_back(nums[right]);
res.insert(out);
++left;
--right;
}else if (sum <target)
left++;
else
right--;
}
}
}
return vector<vector<int>> (res.begin(),res.end());
}
};
``````