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]]
这种是一类问题,即KSum问题
4Sum可以类比于3Sum,做法与3Sum一样。相当于在3Sum的基础上。再嵌套一层for循环。
public class test2 { public static void main(String[] args) { int[] array = {1,0,-1,0,2,-2}; List<List<Integer>> res = new ArrayList<List<Integer>>(); res = fourSum(array,0); for (int i = 0; i < res.size(); i++) { System.out.print("["); for(int j =0;j<res.get(i).size();j++){ System.out.print(res.get(i).get(j)+" "); } System.out.println("]"); } } public static List<List<Integer>> fourSum(int[] nums,int target){ List<List<Integer>> res = new ArrayList<List<Integer>>(); int len = nums.length; if(nums==null || len<4){ return null; } Arrays.sort(nums); for(int i = 0;i<len-3;i++){ for(int j=i+1;j<len-2;j++){ int start = j+1; int end = len-1; while(start<end){ int temp = nums[i]+nums[j]+nums[start]+nums[end]; if(temp==target){ res.add(Arrays.asList(nums[i],nums[j],nums[start],nums[end])); start++; end--; }else if(temp<target){ start++; }else{ end--; } } } } return res; } }