给定一个含有 n 个整数的数组 S,数列 S 中是否存在元素 a,b,c 和 d 使 a + b + c + d = target ?
请在数组中找出所有满足各元素相加等于特定值的不重复组合。
注意:解决方案集不能包含重复的四元组合。
例如,给定数组 S = [1, 0, -1, 0, -2, 2],并且给定 target = 0。
示例答案为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
详见:https://leetcode.com/problems/4sum/description/
实现语言:Java
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List result = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 4){
return result;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i-1]){
continue;
}
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j-1]){
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (left < right) {
int tmp = nums[i] + nums[j] + nums[left] + nums[right];
if (tmp == target) {
List l = new ArrayList<Integer>();
l.add(nums[i]);
l.add(nums[j]);
l.add(nums[left]);
l.add(nums[right]);
result.add(l);
while (left < right && nums[++left] == nums[left-1]);
while (left < right && nums[--right] == nums[right+1]);
} else if (tmp > target){
while (left < right && nums[--right] == nums[right+1]);
} else{
while (left < right && nums[++left] == nums[left-1]);
}
}
}
}
return result;
}
}
参考:https://www.jianshu.com/p/1ec86ec8feb6