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)
思路:与 2Sum解决方法类似,两个指针一个在前,一个在后。
代码实现:
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int>> res;
set<vector<int>> tepres;
int len = num.size();
if(len < 4)
return res;
sort(num.begin(),num.end());
for(int i = 0; i < len;i++){
for(int j = i+1;j<len;j++){
int begin = j + 1;
int end = len - 1;
while(begin < end){
int sum = num[i] + num[j] + num[begin] + num[end];
if(sum == target){
vector<int> tep;
tep.push_back(num[i]);
tep.push_back(num[j]);
tep.push_back(num[begin]);
tep.push_back(num[end]);
tepres.insert(tep);
begin++;
end--;
}
else if(sum < target)
begin++;
else
end--;
}
}
}
set<vector<int>>::iterator it = tepres.begin();
for(;it != tepres.end();it++){
res.push_back(*it);
}
return res;
}
};