4Sum

来源:互联网 发布:c语言排序方法 编辑:程序博客网 时间:2024/05/19 18:11
Problem: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)

对于k-sum问题. 时间复杂度N^(k-1).

public static List<List<Integer>> fourSum(int[] nums, int target) {Arrays.sort(nums);ArrayList<List<Integer>> al=new ArrayList<List<Integer>>();HashSet<List<Integer>> hs=new HashSet<List<Integer>>();for(int i=0;i<nums.length;i++){for(int j=i+1;j<nums.length;j++){int start=j+1,end=nums.length-1;while(start<end){int sum=nums[i]+nums[j]+nums[start]+nums[end];if(sum<target)start++;else if(sum>target)end--;else{ArrayList<Integer> temp=new ArrayList<Integer>();temp.add(nums[i]);temp.add(nums[j]);temp.add(nums[start]);temp.add(nums[end]);if(!hs.contains(temp)){hs.add(temp);al.add(temp);}start++;end--;}}}}return al;}


0 0