similar with 3Sum. O(n3)
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 Arrays.sort(num); 6 HashSet<ArrayList<Integer>> hSet = new HashSet<ArrayList<Integer>>(); 7 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 8 for (int i = 0; i < num.length; i++) { 9 for (int j = i + 1; j < num.length; j++) { 10 for (int k = j + 1, l = num.length - 1; k < l;) { 11 int sum = num[i] + num[j] + num[k] + num[l]; 12 if (sum > target) { 13 l--; 14 } 15 else if (sum < target) { 16 k++; 17 } 18 else if (sum == target) { 19 ArrayList<Integer> found = new ArrayList<Integer>(); 20 found.add(num[i]); 21 found.add(num[j]); 22 found.add(num[k]); 23 found.add(num[l]); 24 if (!hSet.contains(found)) { 25 hSet.add(found); 26 result.add(found); 27 } 28 29 k++; 30 l--; 31 32 } 33 } 34 } 35 } 36 return result; 37 } 38 }