标签:
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:
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)
1 vector<vector<int>> fourSum(vector<int>& nums, int target) { 2 sort(nums.begin(),nums.end()); 3 int len=nums.size(),i,j; 4 int sum,sum1,ileft,iright; 5 vector<vector<int> > res; 6 for(i=0;i<len-3;i++) 7 { 8 if(i > 0 && nums[i] == nums[i-1]) continue; 9 for(j=i+1;j<len-2;j++) 10 {if(j > i+1 && nums[j] == nums[j-1]) continue; 11 sum=nums[i]+nums[j]; 12 ileft=j+1;iright=len-1; 13 while(ileft<iright) 14 { 15 sum1=nums[ileft]+nums[iright]; 16 if(sum1+sum==target) 17 { 18 vector<int> tmp; 19 tmp.push_back(nums[i]); 20 tmp.push_back(nums[j]); 21 tmp.push_back(nums[ileft]); 22 tmp.push_back(nums[iright]); 23 res.push_back(tmp); 24 25 while(ileft<iright) 26 { 27 if(nums[ileft]==nums[ileft+1]) 28 ileft++; 29 else 30 {ileft++;break;} 31 } 32 while(ileft<iright) 33 { 34 if(nums[iright]==nums[iright-1]) 35 iright--; 36 else 37 {iright--;break;} 38 } 39 40 } 41 else if(sum1+sum<target) 42 ileft++; 43 else 44 iright--; 45 } 46 } 47 48 49 //while(left<right&&nums[left]==nums[left+1])left++; 50 //while(left<right&&nums[right]==nums[right-1])right--; 51 52 } 53 return res; 54 }
标签:
原文地址:http://www.cnblogs.com/hexhxy/p/4797928.html