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]
]
本实现没有去重,回头再修改吧
package leetcode; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class leet18 { public static Set<int[]> solution(int[] array,int target){ Set<int[]> set = new HashSet<int[]>(); int[] arr; for(int i = 0;i < array.length - 3;i++){ for(int j = i+1;j < array.length - 2;j++){ for(int k = j+1;k < array.length - 1;k++){ for(int l = k+1;l < array.length;l++){ if(array[i] + array[j] + array[k] + array[l] == target){ arr = new int[]{array[i],array[j],array[k],array[l]}; set.add(arr); } } } } } return set; } public static int[] sort(int[] array){ for(int i = 0;i < array.length;i++){ for(int j = 1;j < array.length - i;j++){ if(array[j] < array[j - 1]){ int temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; } } } return array; } public static void main(String[] args) { int[] s = new int[]{1,0,-1,0,-2,2}; int[] array = leet18.sort(s); System.out.println(Arrays.toString(array)); Set<int[]> set = leet18.solution(array, 0); System.out.println("--------------------------"); Iterator<int[]> iter = set.iterator(); while(iter.hasNext()){ System.out.println(Arrays.toString(iter.next())); } } }