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 class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
HashSet<ArrayList<Integer>> hashset = new HashSet<ArrayList<Integer>>();
List<List<Integer>> rec = new LinkedList<>();//这里还不知道为什么可以这样
if(nums.length<4||nums==null)
return rec;
Arrays.sort(nums);
for(int i=0;i<nums.length-3;i++)
for(int j=i+1;j<nums.length-2;j++)
{
int k = j+1;
int l = nums.length-1;
while(k<l)
{
int sum = nums[i]+nums[j]+nums[k]+nums[l];
if(sum>target)
l--;
else if(sum<target)
k++;
else
{
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(nums[i]);
result.add(nums[j]);
result.add(nums[k]);
result.add(nums[l]);
if(!hashset.contains(result))
hashset.add(result);
k++;
l--;
}
}
}
rec.addAll(hashset);
return rec;
}
}