translation
Given an array s with n numbers, is there an element in Sa, B,c and D's and exactly meeta+ B + C + d = target. Find all the four elements in the array that you don't want to wait for, and equal to target. Note: In the (a, the elements in B,c,d must be arranged from small to large. (a≤B≤C≤D) The result must not be duplicated. For example, given s = {1 0-1 0-2 2},target =0。 A result set is: (-1,0,0,1)(-2, -1,1,2)(-2,0,0,2)
Original
Given anArray S ofn integers, is there elementsa, B, C, andDinchS such thata+ B + C + d = target? Find all unique quadrupletsinch theArray which gives the sum ofTarget. Note:elementsinch aQuadruplet (a, b,c,d) must beinchnon-DescendingOrder. (ie,a≤B≤C≤D) The solutionSetMust notContain duplicate quadruplets. For example, given array S = {1 0-1 0-2 2}, andtarget =0.A SolutionSetis: (-1,0,0,1)(-2, -1,1,2)(-2,0,0,2)
Code
The concrete method is the same as the previous two questions, I will not repeat it.
classSolution { Public: vector<vector<int>>Foursum ( vector<int>& Nums,intTarget) {sort (Nums.begin (), Nums.end ()); vector<vector<int>>ResultintLen = Nums.size (); for(intCurrent =0; Current < Len-3; current++) { for(intSecond = current+1; second<len-2; second++) {intFront = second +1, back = Len-1; while(Front < back) {if(Nums[current]+nums[second] + Nums[front] + Nums[back] < target) front++;Else if(Nums[current] +nums[second]+ Nums[front] + nums[back] > target) back--;Else{ vector<int>V4); v[0]=nums[current]; v[1]=nums[second]; v[2]=nums[front]; v[3]=nums[back]; Result.push_back (v); Do{front++; } while(Front < Back&&nums[front-1] = = Nums[front]); Do{back--; } while(Front < Back&&nums[back +1] = = Nums[back]); } } while(Second < len-2&&nums[second+1]==nums[second]) second++; } while(Current < Len-3&& Nums[current +1] = = Nums[current]) current++; }returnResult }};
The topic that is closely related to this problem is recommended:
Portal: Leetcode 3Sum (3-digit and)
Portal: Leetcode 3Sum Closest (the number of the closest 3 numbers)
Copyright NOTICE: This article is nomasp Couvant original article, without permission is prohibited reprint! Welcome to my blog: http://blog.csdn.net/nomasp
Leetcode 4Sum (4-digit and)