【题目】
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)
【题意】
给定一个数组,从中取4个数使它们的和等于target, 找出全部的组合。
不能有反复;
且组合中各个数升序排列;
【思路】
思路和3Sum的思路全然同样,先确定第一个数,剩下的就又变成3Sum问题了【代码】
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> >result;
int size=num.size();
if(size<4)return result;
sort(num.begin(), num.end()); //排序
for(int p1=0; p1<size-3; p1++){
if(p1!=0&&num[p1]==num[p1-1])continue; //第一个数排重
for(int p2=p1+1; p2<size-2; p2++){
if(p2!=p1+1 && num[p2]==num[p2-1])continue; //第二个数排重
int p3=p2+1;
int p4=size-1;
while(p3<p4){
if(p3!=p2+1 && num[p3]==num[p3-1]){p3++;continue;} //第三个数排重
int sum=num[p1]+num[p2]+num[p3]+num[p4];
if(sum==target){
vector<int> quadruplet;
quadruplet.push_back(num[p1]);
quadruplet.push_back(num[p2]);
quadruplet.push_back(num[p3]);
quadruplet.push_back(num[p4]);
result.push_back(quadruplet);
p3++;p4--;
}
else if(sum>target)p4--;
else p3++;
}
}
}
return result;
}
};