[LeetCode]4Sum

4Sum

Given an array S of n integers, are there elements abc, 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)

四个的时候如果用3Sum的方法会超时。这时候应该想到二分搜索。确定两个值,然后二分搜索剩下的两个值。3Sum也可以用二分查找的方法,确定一个值,然后二分查找。
最后可以用set做一个去重的工作。
 1 class Solution {
 2 public:
 3     vector<vector<int> > fourSum(vector<int> &nums, int target) {
 4         vector<vector<int>> result;
 5         if(nums.size()<4)return result;
 6         sort(nums.begin(),nums.end());
 7         set<vector<int>> tmpres;
 8         for(int i = 0; i < nums.size(); i++)
 9         {
10             for(int j = i+1; j < nums.size(); j++)
11             {
12                 int begin = j+1;
13                 int end = nums.size()-1;
14                 while(begin < end)
15                 {
16                     int sum = nums[i]+ nums[j] + nums[begin] + nums[end];
17                     if(sum == target)
18                     {
19                         vector<int> tmp;
20                         tmp.push_back(nums[i]);
21                         tmp.push_back(nums[j]);
22                         tmp.push_back(nums[begin]);
23                         tmp.push_back(nums[end]);
24                         tmpres.insert(tmp);
25                         begin++;
26                         end--;
27                     }else if(sum<target)
28                         begin++;
29                     else
30                         end--;
31                 }
32             }
33         }
34         set<vector<int>>::iterator it = tmpres.begin();
35         for(; it != tmpres.end(); it++)
36             result.push_back(*it);
37         return result;
38     }
39 };

 

 

 

posted @ 2015-08-24 13:53  Sean_le  阅读(112)  评论(0编辑  收藏  举报