标签:
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] ]
Subscribe to see which companies asked this question
给定n个整数的数组S,是否在 数组S中有元素a,b,c,d,使得a + b + c + d = target?在数组中找出独一无二的四元素组,使得他们之和为target。
注意:
在四元素组(a,b,c,d)中,必须满足非递减排序。 (即a≤b≤c≤d)
该解决方案集中一定不能包含重复的四元素组。
1 class Solution { 2 public: 3 vector<vector<int>> fourSum(vector<int>& nums, int target) { 4 vector<vector<int> > ans; 5 int sz = nums.size(); 6 int i,j,sum2,te; 7 int left,right; 8 set<vector<int> >s; 9 vector<int> tmp; 10 sort(nums.begin(),nums.end() ); 11 for(i = 0;i < sz - 3;i++) { 12 if(i != 0 && nums[i] == nums[i - 1]) continue; 13 for(j = i + 1;j < sz - 2;j++) { 14 if(j != i + 1 && nums[j] == nums[j - 1]) continue; 15 sum2 = nums[i] + nums[j]; 16 left = j + 1;right = sz - 1; 17 while(left < right) { 18 te = sum2 + nums[left] + nums[right]; 19 if(te == target) { 20 tmp.clear(); 21 tmp.push_back(nums[i]);tmp.push_back(nums[j]);tmp.push_back(nums[left]);tmp.push_back(nums[right]); 22 s.insert(tmp); 23 left++;right--; 24 } 25 else if(te < target) { 26 left++; 27 } 28 else{ 29 right--; 30 } 31 } 32 } 33 } 34 set< vector<int> >::iterator it; 35 for(it = s.begin();it != s.end();it++) { 36 ans.push_back(*it); 37 } 38 return ans; 39 } 40 };
标签:
原文地址:http://www.cnblogs.com/njczy2010/p/5745562.html