leetcode@ [18]4Sum
1 struct quadruplet{ 2 int a,b,c,d; 3 quadruplet() {} 4 quadruplet(int aa,int bb,int cc,int dd){ 5 this->a=aa; this->b=bb; this->c=cc; this->d=dd; 6 } 7 bool operator<(const quadruplet& t)const{ 8 if((a-t.a<0)||(a==t.a&&b<t.b)||(a==t.a&&b==t.b&&c<t.c)||(a==t.a&&b==t.b&&c==t.c&&d<t.d)) return true; 9 return false; 10 } 11 }; 12 class Solution { 13 public: 14 vector<vector<int>> fourSum(vector<int>& nums, int target) { 15 sort(nums.begin(),nums.end()); 16 17 vector<vector<int> > ans; ans.clear(); 18 if(nums.size()<=3) return ans; 19 20 int cntAns=0; 21 vector<int> tmp(4); tmp.clear(); 22 set<quadruplet> st; st.clear(); 23 24 int left,right,sum; 25 26 for(int i=0;i<=nums.size()-4;i++){ 27 for(int j=i+1;j<=nums.size()-3;j++){ 28 left=j+1; 29 right=nums.size()-1; 30 while(left<right){ 31 sum=nums[i]+nums[j]+nums[left]+nums[right]; 32 if(sum==target){ 33 tmp.push_back(nums[i]); tmp.push_back(nums[j]); 34 tmp.push_back(nums[left]); tmp.push_back(nums[right]); 35 sort(tmp.begin(),tmp.end()); 36 37 quadruplet quad=quadruplet(tmp[0],tmp[1],tmp[2],tmp[3]); 38 if(!st.count(quad)){ 39 st.insert(quad); 40 ans.resize(++cntAns); 41 ans[cntAns-1]=tmp; 42 } 43 tmp.clear(); 44 45 right--; left++; 46 } 47 else if(sum>target) right--; 48 else left++; 49 } 50 } 51 } 52 53 54 return ans; 55 } 56 };