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> &num,  int target) 
    {
        vector<vector< int>> result;
         if(num.size()< 4return result;
        
        sort(num.begin(),num.end());
         for( int i1= 0;i1<num.size();i1++)
        {
             if(i1> 0 && num[i1]==num[i1- 1])
                 continue;
             for( int i2=i1+ 1;i2<num.size();i2++)
            {
                 if(i2>i1+ 1 && num[i2]==num[i2- 1])
                     continue;
                 int i3=i2+ 1;
                 int i4=num.size()- 1;
                 while(i3<num.size() && i4<num.size() && i3<i4)
                {
                     if(num[i3]+num[i4]==target-num[i1]-num[i2])
                    {
                        vector< int> v;
                        v.push_back(num[i1]);v.push_back(num[i2]);v.push_back(num[i3]);v.push_back(num[i4]);
                        result.push_back(v);
                         do
                        {
                            i3++;
                        } while(i3<num.size()&& num[i3]==num[i3- 1]);
                         do
                        {
                            i4--;
                        } while(i4>i3 && num[i4]==num[i4+ 1]);
                    }
                     else  if(num[i3]+num[i4]<target-num[i1]-num[i2])
                        i3++;
                         else i4--;
                }
            }
        }
         return result;
    }
};

你可能感兴趣的:(SUM)