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:
classSolution{public:vector<vector<int>>fourSum(vector<int>&num,inttarget){// Note: The Solution object is instantiated only once and is reused by each test case.vector<int>tmp;vector<vector<int>>res;if(num.empty())returnres;sort(num.begin(),num.end());for(inti=0;i<num.size();i++){intcur=target-num[i];for(intj=i+1;j<num.size();j++){inttemp=cur-num[j];intstart=j+1,end=num.size()-1;while(start<end){if(num[start]+num[end]==temp){tmp.push_back(num[i]);tmp.push_back(num[j]);tmp.push_back(num[start]);tmp.push_back(num[end]);res.push_back(tmp);tmp.clear();start++;end--;while(start<end&&num[start]==num[start-1])start++;while(start<end&&num[end]==num[end+1])end--;}elseif(num[start]+num[end]<temp){start++;while(start<end&&num[start]==num[start-1])start++;}else{end--;while(start<end&&num[end]==num[end+1])end--;}}while(j<num.size()&&num[j]==num[j+1])j++;}while(i<num.size()&&num[i]==num[i+1])i++;}returnres;}};