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)
就是3Sum前面再加一个数作为第一个数就好
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ret = new ArrayList<>();
int n1=0,n2=0,n3=0,n4=0;
if(nums==null||nums.length<4)return ret;
Arrays.sort(nums);
for(n1=0;n1<nums.length-3;n1++){
while(n1!=0&&n1<nums.length&&nums[n1]==nums[n1-1]){
n1++;
}
if(n1>=nums.length-3)break;
if(nums[n1]>target/4)break;
for(n4=nums.length-1;n4>n1+2;n4--){
while(n4!=nums.length-1&&n4>n1&&nums[n4]==nums[n4+1]){
n4--;
}
if(n4<=n1+2)break;
if(nums[n4]<(target-nums[n1])/3)break;
n2=n1+1;
n3=n4-1;
while(n2<n3){
int t = nums[n1]+nums[n2]+nums[n3]+nums[n4];
if(t>target){
n3--;
while(n3>=0&&nums[n3+1]==nums[n3])n3--;
}else if(t<target){
n2++;
while(n2<nums.length&&nums[n2]==nums[n2-1])n2++;
}else{
List<Integer> r = new ArrayList<>();
r.add(nums[n1]);r.add(nums[n2]);r.add(nums[n3]);r.add(nums[n4]);
ret.add(r);
n2++;while(n2<nums.length&&nums[n2]==nums[n2-1])n2++;
n3--;while(n3>=0&&nums[n3+1]==nums[n3])n3--;
}
}
}
}
return ret;
}
}