给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。
四元组(a, b, c, d)中,需要满足a <= b <= c <= d
答案中不可以包含重复的四元组。
vector<vector<int> > fourSum(vector<int> nums, int target) {
vector<vector<int>> res;
if (nums.size() < 4) {
return res;
}
sort(nums.begin(), nums.end());
for (int first = 0; first < nums.size() - 3;) {
for (int second = first + 1; second < nums.size() - 2;) {
int third = second + 1;
int fourth = nums.size() - 1;
while (third < fourth) {
int sum = nums[first] + nums[second] + nums[third] + nums[fourth];
if (sum == target) {
res.push_back({nums[first], nums[second], nums[third], nums[fourth]});
++third;
while (third < fourth && nums[third - 1] == nums[third]) {
++third;
}
} else if (sum < target) {
++third;
} else {
--fourth;
}
}
++second;
while (second < nums.size() && nums[second - 1] == nums[second]) {
++second;
}
}
++first;
while (first < nums.size() && nums[first - 1] == nums[first]) {
++first;
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。