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.
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]
]
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> lists = new ArrayList<>();
if (nums.length < 4 || nums == null) return lists;
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target)break;
int target1 = target - nums[i];
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i+1 && nums[j] == nums[j - 1]) {
continue;
}
if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target)break;
int target2 = target1 - nums[j];
int k = j + 1;
int m = nums.length - 1;
while (k < m){
if(nums[k] + nums[m] == target2){
List<Integer> ll = new ArrayList<>();
ll.add(nums[i]);
ll.add(nums[j]);
ll.add(nums[k]);
ll.add(nums[m]);
lists.add(ll);
k++;
m--;
while(k < m && nums[k] == nums[k - 1]) k++;
while(k < m && nums[m] == nums[m + 1]) m--;
}
else if (nums[m] + nums[k] > target2) {
m--;
}else{
k++;
}
}
}
}
return lists;
}