题目描述
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.
解法
- 解法和2sum、3sum问题类似,先对数组排序,然后对选定区间进行双指针法查找
- 与2sum和3sum不同的是,4sum问题需要先选定两个下标,再在右子区间进行双指针查找
- 需要注意每层循环都要去掉重复数字
- 代码实现
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int>> res;
if(num.empty())
return res;
sort(num.begin(), num.end());
for(int i = 0; i < num.size(); ++i) {
for(int j = i + 1; j < num.size(); ++j) {
int left = j + 1, right = num.size() - 1;
while(left < right) {
int curSum = num[i] + num[j] + num[left] + num[right];
if(curSum == target) {
vector<int> tmp = {num[i], num[j], num[left], num[right]};
res.push_back(tmp);
while(left < right && num[left] == num[left + 1])
++left;
while(left < right && num[right - 1] == num[right])
--right;
++left;
--right;
} else if(curSum < target)
++left;
else
--right;
}
while(j < num.size() && num[j] == num[j + 1])
++j;
}
while(i < num.size() && num[i] == num[i + 1])
++i;
}
return res;
}
};