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: 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]]
classSolution { Public: Vector<vector<int>> Foursum (vector<int>& Nums,inttarget) { intL =nums.size (), sum, left, right, I, J; Vector<vector<int>>ans; if(l<4) returnans; Sort (Nums.begin (), Nums.end ()); for(i =0; I<l-3; i++) { if(i && nums[i] = = nums[i-1]) Continue; for(j = i +1; J<l-2; J + +) { if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) Break; if(nums[i]+nums[j]+nums[l-2]+nums[l-1]<target)Continue; if(J>i +1&& Nums[j] = = Nums[j-1]) Continue; Sum= Nums[i] +Nums[j]; Left= j +1; Right= L-1; while(Left <Right ) { if(sum + nums[left] + nums[right] = =target) Ans.push_back ({nums[i], nums[j], Nums[left+ +], nums[right--] }); Else if(sum + nums[left] + Nums[right] <target) left++; Else Right--; while(left>j+1&& Nums[left] = = Nums[left-1]) left++; while(right<l-1&& Nums[right] = = Nums[right +1]) right--; } } } returnans; }};
4Sum--Find the 4 numbers in the array and the target