1 Topics:
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)
2 Ideas
First, you have to understand 3Sum.
Then follow the idea of 3Sum, it is good to do. The main one is to traverse all four combinations. The sort is sure. See the code for details and think for yourself. Time complexity O (n^3) did a few questions, feeling a bit of a state.
3 Code
PublicList<list<integer>> Foursum (int[] Nums,inttarget) {List<List<Integer>> result =NewArraylist<list<integer>>(); intLen =nums.length; if(Len < 4){ returnresult; } arrays.sort (Nums); intHead = 0; intEnd = Len-1; while(Head < End-2){ while(Head < End-2){ intPre = head + 1; intsuffix = end-1; /*Compare all four group between pre & Suffic*/ while(Pre <suffix) { intsum = nums[head]+nums[end]+nums[pre]+Nums[suffix]; if(Sum <target) { ++Pre; }Else if(Sum >target) { --suffix; }Else{result.add (Arrays.aslist (Nums[head],nums[pre],nums[suffix],nums[end])); ++Pre; --suffix; while(Pre <= suffix && nums[pre]==nums[pre-1]) + +Pre; while(Pre <= suffix && nums[suffix]==nums[suffix+1])--suffix; } } /*for each nums[head], Compore all Nums[head] until head<end-2*/++Head; while(Head<end-2 && nums[head]==nums[head-1]) + +Head; } /*set head to 0 & End-1, so we can traverse all four groups*/Head=0; --end; while(head<end-2 &&nums[end] = = nums[end+1])--end; } returnresult; }
[Leetcode 18]4sum