您的位置:首页 > 其它

leetcode 第18题 4Sum

2015-04-26 09:54 316 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  4Sum