问题描述
- Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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. - Example
Given array nums = [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]
]
问题分析
- 该题是 Leetcode-1. Two Sum 以及 Leetcode-264. Two Sum II - Input array is sorted 以及 LeetCode 15. 3Sum 进阶题目。做法也类似。
- 该题是在 3Sum 基础上再加一层外循环即可。
经验教训
- 由 2Sum, 3Sum, 4Sum 推导出 k Sum
代码实现
public List<List<Integer>> fourSum(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return new ArrayList<>();
}
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<List<Integer>>();
for (int i = 0; i < nums.length ; i++) {
if (i != 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length ; j++) {
if (j != i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
int sum = target - nums[i] - nums[j];
while (left < right) {
if (nums[left] + nums[right] == sum) {
ArrayList<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[left++]);
list.add(nums[right--]);
res.add(list);
while (left < right && nums[left] == nums[left - 1]) {
++left;
}
while (left < right && nums[right] == nums[right + 1]) {
--right;
}
}else if (nums[left] + nums[right] < sum) {
++left;
}else {
--right;
}
}
}
}
return res;
}