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]
]
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
if (nums.empty())
return res;
sort(nums.begin(), nums.end());
int len = nums.size();
for (int i = 0; i < len;i++) {
for (int j = i + 1;j < len;j++) {
int m = j + 1, n = len- 1;
while (m < n) {
vector<int> v;
int sum = nums[i] + nums[j] + nums[m] + nums[n];
if (sum == target) {
v.push_back(nums[i]);
v.push_back(nums[j]);
v.push_back(nums[m]);
v.push_back(nums[n]);
res.push_back(v);
while (m + 1 < len&&nums[m] == nums[m + 1])
++m;
while (n > 0 && nums[n] == nums[n - 1])
--n;
++m;
--n;
}
else if (sum < target) {
while (m + 1 < len&&nums[m] == nums[m + 1])
++m;
++m;
}
else {
while (n > 0 && nums[n] == nums[n - 1])
--n;
--n;
}
}
while (j + 1 < len&&nums[j] == nums[j + 1])
++j;
}
while (i + 1 < len&&nums[i] == nums[i + 1])
++i;
}
return res;
}
};