18. 4Sum(C++)
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: 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>> res; 5 if(nums.empty()) return res; 6 std::sort(nums.begin(),nums.end()); 7 int len=nums.size(); 8 for(int i1=0;i1<len;i1++){ 9 for(int i2=i1+1;i2<len;i2++){ 10 int i3=i2+1; 11 int i4=len-1; 12 while(i3<i4){ 13 int sum=nums[i1]+nums[i2]+nums[i3]+nums[i4]; 14 if(sum>target){ 15 i4--; 16 }else if(sum<target){ 17 i3++; 18 }else{ 19 vector<int> tmp(4,0); 20 tmp[0]=nums[i1]; 21 tmp[1]=nums[i2]; 22 tmp[2]=nums[i3]; 23 tmp[3]=nums[i4]; 24 res.push_back(tmp); 25 while(i3<i4&&nums[i3]==tmp[2]) i3++; 26 while(i3<i4&&nums[i4]==tmp[3]) i4--; 27 } 28 } 29 while(i2+1<len&&nums[i2]==nums[i2+1]) i2++; 30 } 31 while(i1+1<len&&nums[i1]==nums[i1+1]) i1++; 32 } 33 return res; 34 } 35 };