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:
Elements in a quadruplet (a,b,c,d) must being in the 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)
Four number of added and target numbers in a given array
The way to solve problems: double pointers, same as 3Sum
Code:
public class Solution {public list<list<integer>> foursum (int[] nums, int target) {list<list&
lt;integer>> result = new arraylist<list<integer>> ();
Arrays.sort (Nums); for (int i = 0; i < nums.length-3 i++) {if (i > 0 && nums[i] = = Nums[i-1]) {C
Ontinue; for (int j = i + 1; j < Nums.length-2; J + +) {if (J > i + 1 && nums[j] = = Nums [J-1])
{continue;
int k = j + 1;
int L = nums.length-1;
while (K < L) {if (K > J + 1 && nums[k] = = Nums[k-1]) {k++;
Continue
} if (L < nums.length-1 && nums[l] = = nums[l + 1]) {l--;
Continue
} int sum = Nums[i] + nums[j] + nums[k] + nums[l];
if (sum = = target) {list<integer> temp = new arraylist<integer> ();
Temp.add (Nums[i]);
Temp.add (Nums[j]);
Temp.add (Nums[k]);
Temp.add (Nums[l]);
Result.add (temp);
k++;
l--;
}else if (sum < target) {k++;
}else{l--;
}}} return result; }
}