18. 4Sum
https://leetcode.com/problems/4sum/#/solutions
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] ]
public class Solution {
public List<List<Integer>> fourSum(int[] num, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (num==null || num.length==0) return res;
Arrays.sort(num);
int max = num[num.length-1];
if (4 * num[0] > target || 4 * max < target)
return res;
for (int i=num.length-1; i>=3; i--) {
if (i<num.length-1 && num[i]==num[i+1]) continue;
threeSum(0, i-1, num, target-num[i], res, num[i]);
}
return res;
}
public void threeSum(int start, int end, int[] num, int target, List<List<Integer>> res, int last1) {
for (int i=end; i>=2; i--) {
if (i<end && num[i]==num[i+1]) continue;
twoSum(0, i-1, num, target-num[i], res, num[i], last1);
}
}
public void twoSum(int l, int r, int[] num, int target, List<List<Integer>> res, int last2, int last1) {
while (l < r) {
if (num[l]+num[r] == target) {
List<Integer> set = new ArrayList<Integer>();
set.add(num[l]);
set.add(num[r]);
set.add(last2);
set.add(last1);
res.add(new ArrayList<Integer>(set));
l++;
r--;
while (l<r && num[l] == num[l-1]) {
l++;
}
while (l<r && num[r] == num[r+1]) {
r--;
}
}
else if (num[l]+num[r] < target) {
l++;
}
else {
r--;
}
}
}
}