# [LeetCode]4Sum

## 原题

Given an array `nums` of n integers and an integer `target`, are there elements abc, and d in `nums` 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.

Example:

```Given array nums = [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]
]
```

## 题解

```class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector< vector<int> > rs;
sort(nums.begin(), nums.end());
int l = nums.size(), f = 0, b = 0;
for (int i = 0; i < l - 3; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < l - 2; j++) {
f = j + 1;
b = l - 1;
if (j - i > 1 && nums[j] == nums[j - 1]) continue;
while (f < b) {
if (nums[i] + nums[j] + nums[f] + nums[b] < target) {
while (nums[f] == nums[++f]) {}
} else if(nums[i] + nums[j] + nums[f] + nums[b] > target) {
while (nums[b] == nums[--b]) {}
} else {
vector<int> tmp = {nums[i], nums[j], nums[f], nums[b]};
rs.push_back(tmp);
while (nums[f] == nums[++f]) {}
while (nums[b] == nums[--b]) {}
}
}
}
}
return rs;
}
};
```