Given an array nums
of n integers and an integer target
, are there elements a, b, c, 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) {
int n = nums.size();
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
int l = j + 1, r = n - 1;
while (l < r) {
int sum = nums[i] + nums[j] + nums[l] + nums[r];
if (sum == target) {
ans.push_back({nums[i], nums[j], nums[l], nums[r]});
l++;
r--;
while (nums[l] == ans.back()[2]) {
l++;
}
while (nums[r] == ans.back()[3]) {
r--;
}
}
else if (sum > target) {
r--;
}
else {
l++;
}
}
while (nums[j] == nums[j + 1]) {
j++;
}
}
while (nums[i] == nums[i + 1]) {
i++;
}
}
return ans;
}
};