18. 4Sum

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> fourSum(int[] nums, int target) {
        HashSet> hashset = new HashSet>();
        List> rec = new LinkedList<>();//这里还不知道为什么可以这样
        if(nums.length<4||nums==null)
          return rec;
        Arrays.sort(nums);
        
        for(int i=0;itarget)
                        l--;
                     else if(sum result = new ArrayList();
                            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;
    }
}

你可能感兴趣的:(18. 4Sum)