4Sum
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.
Give an array, and a target integer, to a,b,c,d and satisfy all the combinations in the array that make and target A<=b<=c<=d
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]
]
reference: 3sum
Public list<list<integer>> foursum (int[] nums, int target) {list<list<integer>> ret = new Array
List<> ();
if (nums = null | | Nums.length < 3) return RET;
int len = nums.length;
Arrays.sort (Nums);
Note that for Num[i], when looking for another two numbers, just start looking from i+1.
This style of writing avoids repetition in the result set, because the array is ordered,//So when a number is placed in the result set, the following and its equivalent are skipped directly.
for (int i = 0; i < len; i++) {//Avoid repetition ....
if (i > 0 && nums[i] = = Nums[i-1]) continue;
for (int j = i + 1; j < Len; J +) {//Note J if (J > i + 1 && nums[j] = = Nums[j-1]) continue;
Look backwards, avoid repeating int begin = j + 1;
int end = Len-1;
while (begin < end) {int sum = Nums[i] + nums[j] + Nums[begin] + nums[end];
if (sum = = target) {list<integer> List = new arraylist<> ();
List.add (Nums[i]);
List.add (Nums[j]);
List.add (Nums[begin]);
List.add (Nums[end]);
Ret.add (list);
begin++;
end--; Avoid duplication。。。。
while (Begin < end && Nums[begin] = = nums[begin-1]) begin++;
while (Begin < end && Nums[end] = = nums[end + 1]) end--;
else if (sum > Target) end--;
else begin++;
}} return ret; }