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] ]此题与2Sum, 3Sum,3Sum Closest联系在一起,很好解答,注意去掉重复的解即可。
程序如下所示:
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> llst = new ArrayList<>();
List<Integer> lst = null;
Arrays.sort(nums);
for (int i = 3; i < nums.length; ++ i){
if (i != nums.length - 1&&nums[i] == nums[i+1]){
continue;
}
int threeSum = target - nums[i];
for (int j = 2; j < i; ++ j){
if (j != i - 1&&nums[j] == nums[j+1]){
continue;
}
int twoSum = threeSum - nums[j];
int l = 0, r = j - 1;
while (l < r){
if (nums[l] + nums[r] < twoSum){
l ++;
}
else if (nums[l] + nums[r] > twoSum){
r --;
}
else {
lst = new ArrayList<>();
lst.add(nums[l]);
lst.add(nums[r]);
lst.add(nums[j]);
lst.add(nums[i]);
while (l < r&&nums[l] == nums[l+1]) l++;
while (r > l&&nums[r] == nums[r-1]) r--;
llst.add(lst);
l ++;
r --;
}
}
}
}
return llst;
}
}