[LeetCode] 4Sum

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, abcd)
  • 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基础上稍做改动写的程序
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        vector<vector<int> > result;
        int len = num.size();
        if(len<4)
            return result;
        int sum;
        sort(num.begin(),num.end());
        for(int mid2 = 2;mid2<len-1;mid2++){
        
            for(int mid = 1;mid<mid2;mid++){
               int low = 0,up = len-1;
               while(low<mid && mid2<up){
                   if(low < mid-1 && low>0 && num[low] == num[low-1]){
                       low++;
                       continue;
                   }
                   if(up > mid2+1 && up<len-1 && num[up] == num[up+1]){
                       up--;
                       continue;
                   }
                   sum  = num[low] + num[mid] + num[mid2] + num[up];
                   if(sum == target){
                       vector<int> temp;
                       temp.push_back(num[low]);
                       temp.push_back(num[mid]);
                       temp.push_back(num[mid2]);
                       temp.push_back(num[up]);
                       if(find(result.begin(),result.end(),temp)== result.end())
                           result.push_back(temp);
                   
                   }else if(sum>target){
                      up--;
                      continue;
                   }else
                   {
                      low++;
                      continue;
                   }
                low++;
                up--;

               }//end while
            }//end for
        }//end for
        return result;
    }
};

 

posted @ 2014-08-11 22:05  Xylophone  Views(129)  Comments(0Edit  收藏  举报