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 be 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)
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
int i,j,k,p,n=nums.length;
List<List<Integer>> resList = new ArrayList<List<Integer>>();
//Sort the array
Arrays.sort(nums);
if (n<4) return resList;
for(i=0;i<n-3;i++){
if(i==0 || nums[i]>nums[i-1]){
for(j=i+1;j<n-2;j++){
if(j==i+1 || nums[j]>nums[j-1]){
k=j+1;
p=n-1;
//two pointer method
while(k<p){
List<Integer> res = new ArrayList<Integer>();
if(nums[i]+nums[j]+nums[k]+nums[p]==target){
res.add(nums[i]);
res.add(nums[j]);
res.add(nums[k]);
res.add(nums[p]);
resList.add(res);
k++;
p--;
while(k<p && nums[p]==nums[p+1]) p--;
while(k<p && nums[k]==nums[k-1]) k++;
}else if(nums[i]+nums[j]+nums[k]+nums[p]<target)
k++;
else
p--;
}
}
}
}
}
return resList;
}
}