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:
- 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)
在3Sum的基础上稍微修改即可,O(n ^ 3)。
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 Arrays.sort(num); 5 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 6 if(num == null || num.length < 4) return result; 7 int len = num.length; 8 for(int i = 0; i <= num.length - 4; i ++){ 9 if(i==0 || num[i] > num[i-1]){ 10 for(int a = num.length - 1; a > i + 2; a --){ 11 if(a == num.length - 1 || num[a] < num[a + 1]){ 12 int j = i + 1; 13 int h = a - 1; 14 while(j < h){ 15 int sum = num[j] + num[h] + num[i] + num[a]; 16 if(sum == target){ 17 ArrayList<Integer> row = new ArrayList<Integer>(); 18 row.add(num[i]); 19 row.add(num[j]); 20 row.add(num[h]); 21 row.add(num[a]); 22 result.add(row); 23 h--; 24 j++; 25 while(h>j && num[h]==num[h+1]) h--; 26 27 while(j<h && num[j]==num[j-1]) j++; 28 }else if(sum < target){ 29 j ++; 30 }else if(sum > target){ 31 h --; 32 } 33 } 34 } 35 } 36 } 37 } 38 return result; 39 } 40 }
posted on 2013-10-17 11:58 Step-BY-Step 阅读(164) 评论(0) 编辑 收藏 举报