Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
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.
Example:
Given array nums = [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] ]
原本想着将4Sum转化为两个2Sum,做到一半发现这两个2Sum会有重叠,无奈放弃,看了视频教程是将4sum转化为3sum然后再转化为2sum。吐血
1 class Solution { 2 public boolean isSame(List<Integer> a,List<Integer> b){ 3 for (int i = 0; i < 4; i++) { 4 int aa = a.get(i); 5 int bb = b.get(i); 6 if (aa != bb) 7 return false; 8 } 9 return true; 10 } 11 public List<List<Integer>> fourSum(int[] nums, int target) { 12 List<List<Integer>> result = new ArrayList<>(); 13 Arrays.sort(nums); 14 for (int i = 0; i < nums.length - 3; i++) { 15 if (i == 0 || nums[i] != nums[i-1]){//去重 16 //化为3Sum 17 for (int j = i + 1; j < nums.length - 2; j++) { 18 if (j == i + 1 || nums[j] != nums[j - 1]){//去重 19 //化为2Sum 20 int newTarget = target - nums[i] - nums[j]; 21 int low = j+1,high=nums.length-1; 22 while (low < high){ 23 int sum = nums[low]+nums[high]; 24 if (sum > newTarget){ 25 --high; 26 }else if (sum < newTarget){ 27 ++low; 28 }else{ 29 if (result.size() > 0) { 30 List<Integer> l = result.get(result.size() - 1); 31 if (!isSame(l,Arrays.asList(nums[i], nums[j], nums[low], nums[high]))) { 32 result.add(Arrays.asList(nums[i], nums[j], nums[low], nums[high])); 33 // System.out.println(nums[i] + "," + nums[j] + "," + nums[low] + "," + nums[high]); 34 } 35 }else { 36 result.add(Arrays.asList(nums[i], nums[j], nums[low], nums[high])); 37 // System.out.println(nums[i] + "," + nums[j] + "," + nums[low] + "," + nums[high]); 38 } 39 ++low; 40 } 41 } 42 } 43 } 44 } 45 } 46 return result; 47 } 48 }