4Sum
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)
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)
Reference:
My Solutions:
class Solution {
public:
class Mysum{
public:
int sum;
int index[2];
bool operator<(const Mysum& other)const{
return sum<other.sum;
}
bool check(const Mysum& other)const{
for(int i=0;i<2;++i){
for(int j=0;j<2;++j){
if(index[i]==other.index[j])
return false;
}
}
return true;
}
};
vector<vector<int> > fourSum(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<Mysum> mysums;
vector<vector<int> > result;
sort(num.begin(),num.end());
for(int i=0;i<num.size();++i){
for(int j=i+1;j<num.size();++j){
Mysum tmp;
tmp.sum=num[i]+num[j];
tmp.index[0]=i;
tmp.index[1]=j;
mysums.push_back(tmp);
}
}
sort(mysums.begin(),mysums.end());
for(int i=0;i<mysums.size();++i){
Mysum tmp;
tmp.sum=target-mysums[i].sum;
vector<Mysum>::iterator low=lower_bound(mysums.begin()+i+1,mysums.end(),tmp);
for(;low!=mysums.end()&&low->sum==tmp.sum;++low){
if(mysums[i].check(*low)){
vector<int> r;
r.push_back(num[mysums[i].index[0]]);
r.push_back(num[mysums[i].index[1]]);
r.push_back(num[low->index[0]]);
r.push_back(num[low->index[1]]);
sort(r.begin(),r.end());
if(find(result.begin(),result.end(),r)==result.end()){
result.push_back(r);
}
}
}
}
return result;
}
};