Question:
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)
Solution:
1 class Solution { 2 public: 3 vector<vector<int>> fourSum(vector<int>& nums, int target) { 4 vector< vector<int> > result; 5 sort(nums.begin(),nums.end()); 6 if(nums.size()<4) 7 return result; 8 for(auto i=nums.begin();i!=nums.end()-3;i++) 9 { 10 for(auto j=i+1;j!=nums.end()-2;j++) 11 { 12 auto p=j+1; 13 auto q=nums.end()-1; 14 while(p<q) 15 { 16 if(*i+*j+*p+*q<target) 17 { 18 p++; 19 } 20 else if(*i+*j+*p+*q>target) 21 { 22 q--; 23 } 24 else 25 { 26 vector<int> temp; 27 temp.push_back(*i); 28 temp.push_back(*j); 29 temp.push_back(*p); 30 temp.push_back(*q); 31 result.push_back(temp); 32 q--; 33 } 34 } 35 } 36 } 37 sort(result.begin(),result.end()); 38 auto it=unique(result.begin(),result.end()); 39 result.erase(it,result.end()); 40 return result; 41 42 } 43 };