Question:
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: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]
]
Algorithm:
First sort, two-tier loops to determine two-digit nums[i],nums[j], then use two pointers m,n from I+1, Nums.size () forward Search
Note that during traversal, there are repeated accepted Code to be moved backwards:
Class Solution {public:vector<vector<int>> foursum (vector<int>& nums, int target) {ve
ctor<vector<int>> Res;
if (Nums.size () <4) return res;
Sort (Nums.begin (), Nums.end ());
for (int i=0;i<nums.size () -3;i++) {if (i>0&&nums[i]==nums[i-1]) continue; for (int j=i+1;j<nums.size () -2;j++) {if (j> (i+1) &&nums[j]==nums[j-1]
) continue;
int m=j+1;
int N=nums.size ()-1;
while (M < n) {if (m> (j+2) &&nums[m]==nums[m-1]) {
m++;
Continue } if (n< (Nums.size ()-1) &&nums[n]==nums[n+1]) {n
--;
Continue
} int sum=nums[i]+nums[j]+nums[m]+nums[n];
if (sum==target) {vector<int> tmp={nums[i],nums[j],nums[m],nums[n]};
Res.push_back (TMP);
m++;
n--;
else if (sum>target) n--;
else m++;
}} return res; }
};