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)
Solution1:
A typical k-sum problem. Time is N to the poser of (k-1).
Run time complexity is O(n^3), solution based on 3sum
the efficiency of the best solution for m sum is O(n^(m-1))
public class Solution { public ArrayList> fourSum(int[] num, int target) { ArrayList > result = new ArrayList >(); HashSet > check = new HashSet >(); Arrays.sort(num); if(num.length < 4) return result; for(int i = 0; i < num.length; i++) { //3 sum for(int j = i + 1; j < num.length; j++) { int start = j + 1; int end = num.length - 1; //2 sum while(start < end) { int sum = num[i] + num[j] + num[start] + num[end]; ArrayList temp = new ArrayList (); if(sum == target) { temp.add(num[i]); temp.add(num[j]); temp.add(num[start]); temp.add(num[end]); if(!check.contains(temp)) { result.add(temp); check.add(temp); } start++; end--; }else if(sum < target) { start++; }else { end--; } } } } return result; } }
No comments:
Post a Comment