您的位置:首页 > 其它

4Sum

2015-08-12 10:07 281 查看
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)
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
int ln=num.size();
vector<vector<int>> avec;
if(ln<4)
return avec;
vector<int>::iterator iter=num.begin();
sort(num.begin(), num.end());
int t,l,h;
for(int a=0;a<ln-3;a++){
for(int b=a+1;b<ln-2;b++){
l=b+1;
h=num.size()-1;
vector<int> res(4);
t=target-num[a]-num[b];
while(l<h){
int s=num[l]+num[h];
if(s<t){
l++;
continue;
}
if(s>t){
h--;
continue;
}
if(s==t){
res[0]=num[a];
res[1]=num[b];
res[2]=num[l];
res[3]=num[h];
avec.push_back(res);
//res.clear();
l++;
h--;
}
}
}
}
vector<vector<int> > ans;
for(int i = 0; i < avec.size(); ++i)
if(find(ans.begin(), ans.end(), avec[i]) == ans.end()) //find函数应用
ans.push_back(avec[i]);
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: