leetcode 44: 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, 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) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > rel; int sz = num.size(); if(sz<4) return rel; sort( num.begin(), num.end() ); set< vector<int> > mySet; for( int i=0; i<sz-3; i++) { for( int j=i+1; j<sz-2; j++) { int l = j + 1; int h = sz-1; while( l < h) { int temp = num[i] + num[j] + num[l] + num[h]; if( temp == target){ vector<int> vec; vec.push_back( num[i]); vec.push_back( num[j]); vec.push_back( num[l]); vec.push_back( num[h]); if( mySet.find( vec ) == mySet.end() ) { rel.push_back( vec ); mySet.insert( vec ); } ++l; --h; } else if( temp < target) { ++l; } else { --h; } } } } return rel; } };