title :
Given an array S of n integers, is 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 is 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)
Code :
classSolution { Public: Vector<vector<int> > Foursum (vector<int> &num,inttarget) {Vector<vector<int> >result; Sort (Num.begin (), Num.end ()); unsignedintLen =num.size (); if(len<4)returnresult; for(inti =0; I < len-3; ++i) {if(i>0&& num[i]==num[i-1] )Continue; for(intj = len-1; j>i+2; --j) {if(j<len-1&& num[j]==num[j+1] )Continue; intK = i+1; intZ = j1; while(k<z) {Const intTmp_sum = num[i]+num[j]+num[k]+Num[z]; if(tmp_sum==target) {Vector<int>tmp; Tmp.push_back (Num[i]); Tmp.push_back (Num[k]); Tmp.push_back (Num[z]); Tmp.push_back (Num[j]); Result.push_back (TMP); ++K; while(num[k]==num[k-1] && k<z) + +K; --Z; while(num[z]==num[z+1] && k<z)--Z; } Else if(tmp_sum>target) { --Z; while(num[z]==num[z+1] && k<z)--Z; } Else { ++K; while(num[k]==num[k-1] && k<z) + +K; } } } } returnresult; }};
Tips:
1. The above code time Complexity O (n³) is not optimal, there are some other possible ways to do O (n²) in HashMap way.
2. The above code follows the same idea as 3Sum:
A. 3Sum needs to fix a variable in one Direction, set a pointer at each head and tail, and move toward the middle.
B. 4Sum because of a variable, you need to fix the head and fixed the tail, set a pointer in the inner end, and then toward the middle approximation.
3. Twosum 3Sum 4Sum This is the end of the series. The basic is the fixed head or tail of the variable to the middle force
"4Sum" CPP