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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- 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)
先排序,两层for循环从左往右扫描第一个值和第二个值a1 a2,然后在第二个值的右边,搜索和为target-a1-a2;
第三个a3和第四个数a4的扫面相当于2sum,因为是有序的,用两个指针指向大于a2的最左边和最右边如果 sum<target,左指针++,若 sum<target右指针--;
这里要考虑结果重复的情况。当里层循环结束时,肯定会把外层循环值的可能的所有情况都列出,所以外层循环值应该向后推移到不等于当前值的地方。
对于第三个值和第四个值,当找到符合的a3 a4时,将a3 a4 向右 左推移到不同于当前值的下标。
测试用例{1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,55,6,7} ,11 3
{1,1,1}
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
sort(num.begin(), num.end());
vector<vector<int>>rst;
vector<int>v;
for(int i = 0 ; i < num.size(); ++i)
{
//if(i > 0 && num[i] == num[i - 1])continue;
for(int j = i + 1; j < num.size(); ++j)
{
//if(num[j] == num[j - 1])continue;
int l = j + 1, r = num.size() - 1;
while(l < r)
{
int sum = num[i] + num[j] + num[l] + num[r];
if(sum < target)
{
l++;
}
else if(sum > target)
{
r--;
}
else
{
v.push_back(num[i]);v.push_back(num[j]);
v.push_back(num[l]);v.push_back(num[r]);
rst.push_back(v);
v.clear();
while(l < r && num[l] == num[l + 1])l++;//左右推移时考虑推移的边界
while(r > l && num[r] == num[r - 1])r--;
l++;
r--;
}
//cout<<l<<" "<<r<<endl;
}
while(j < num.size() - 1 && num[j] == num[j + 1])j++;//当前值的里层循环结束后,以当前值开头的所有值都列出,
//推移到与当前值不相等的值
}
while(i < num.size() - 1 && num[i] == num[i + 1])i++;
}
return rst;
}
};