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)
2013-07-04
只能通过小数据,使用的方法和3Sum类似,使用4个指针。
1 public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { 2 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 3 int len = num.length; 4 if(len < 4) 5 return result; 6 Arrays.sort(num); 7 for(int i = 0; i < len - 3; i ++){ 8 for(int j = i + 1; j < len - 2; j++){ 9 int m = j + 1; 10 int n = len -1; 11 while(m < n){ 12 int sum = num[m] + num[n]; 13 if(sum == target - num[i] - num[j]){ 14 ArrayList<Integer> list = new ArrayList<Integer>(); 15 list.add(num[i]); 16 list.add(num[j]); 17 list.add(num[m]); 18 list.add(num[n]); 19 result.add(list); 20 m ++; 21 n --; 22 while(m < n && num[m - 1] == num[m]) m++; 23 while(m < n && num[n] == num[n + 1]) n--; 24 } else if(sum < target - num[i] - num[j]){ 25 m ++; 26 } else { 27 n --; 28 } 29 30 } 31 while(j < len -3 && num[j] == num[j + 1]) j++; 32 } 33 while(i < len - 4 && num[i] == num[i + 1]) i++; 34 } 35 return result; 36 }