首页 > 代码库 > 4Sum

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)

思路:

 1 class Solution { 2 public: 3     vector<vector<int>> fourSum( vector<int> &num, int target ) { 4         set<vector<int>> quadrupletSet; 5         sort( num.begin(), num.end() ); 6         vector<int> quadruplet( 4, -1 ); 7         for( int s1 = (int)num.size()-4; s1 >= 0; --s1 ) { 8             if( target < 4*num[s1] ) { continue; } 9             for( int e1 = (int)num.size()-1; e1 > s1+2; --e1 ) {10                 if( target > 4*num[e1] ) { break; }11                 int s2 = s1+1, e2 = e1-1;12                 while( s2 < e2 ) {13                     int sum = num[s1] + num[e1] + num[s2] + num[e2];14                     if( sum == target ) {15                         quadruplet[0] = num[s1];16                         quadruplet[3] = num[e1];17                         quadruplet[1] = num[s2];18                         quadruplet[2] = num[e2];19                         quadrupletSet.insert( quadruplet );20                         ++s2; --e2;21                     } else if( sum < target ) {22                         ++s2;23                     } else {24                         --e2;25                     }26                 }27             }28         }29         vector<vector<int>> quadruplets;30         for( auto iter = quadrupletSet.begin(); iter != quadrupletSet.end(); ++iter ) {31             quadruplets.push_back( *iter );32         }33         return quadruplets;34     }35 };

 

4Sum