18. 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)

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
       sort(nums.begin(), nums.end());
       vector<vector<int>> result;
       vector<int> temp;
       int len = nums.size();
       int i =0;
       while(i <len-3){
           int j = i+1;
           while(j < len-2){
               int k = j +1, w = len-1;
               while(k <w)
               {
                   int sum = nums[i] + nums[j] + nums[k] + nums[w];
                   if(sum==target)
                   {
                        temp.push_back(nums[i]);
                        temp.push_back(nums[j]);
                        temp.push_back(nums[k]);
                        temp.push_back(nums[w]);
                        result.push_back(temp);
                        temp.clear();
                        k++;
                        w--;
                         while(k < w && nums[k]==nums[k-1])
                            k++;
                        while(k < w && nums[w]==nums[w+1])
                            w--;
                   }else if(sum < target)
                   {
                       k++;
                        while(k < w && nums[k]==nums[k-1])
                            k++;
                   }else
                   {
                       w--;
                         while(k < w && nums[w]==nums[w+1])
                            w--;
                   }
               }
               j++;
                while(j < len-2 && nums[j]==nums[j-1])
                            j++;
           }
           i++;
            while(i < len-3 && nums[i]==nums[i-1])
                            i++;
       }
      return result; 
    }
};


你可能感兴趣的:(18. 4Sum)