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] ]
AC代码
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
List<Integer> ans = new ArrayList<>();
helper(nums, target, res, ans, 0, 4);
return res;
}
private void helper(int[] nums, int target, List<List<Integer>> res,
List<Integer> ans, int cur, int ksum) {
if (nums.length - cur < ksum || ksum < 2 // 长度不够了
|| target < nums[cur] * ksum || target > nums[nums.length - 1] * ksum) return; // 不可能存在ksum元组
if (ksum == 2) {
helpTwoSum(nums, target, res, ans, cur);
} else {
for (int i = cur; i < nums.length; i++) {
if (i > cur && nums[i - 1] == nums[i]) continue; // 去重
ans.add(nums[i]);
helper(nums, target - nums[i], res, ans, i + 1, ksum - 1);
ans.remove(ans.size() - 1);
}
}
}
private void helpTwoSum(int[] nums, int target, List<List<Integer>> res,
List<Integer> ans, int cur) {
int lo = cur;
int hi = nums.length - 1;
while (lo < hi) {
int sum = nums[lo] + nums[hi];
if (sum < target) {
lo++;
} else if (sum > target) {
hi--;
} else {
List<Integer> tmp = new ArrayList<>(ans);
tmp.add(nums[lo]); tmp.add(nums[hi]);
res.add(tmp);
lo++; hi--;
while (lo < hi && nums[lo] == nums[lo - 1]) lo++;
while (lo < hi && nums[hi] == nums[hi + 1]) hi--;
}
}
}
}
本题还可以使用回溯来求解,但是运行时间较长,报错LTE了,但是也可以作为一种思路:
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> ans = new ArrayList<>();
Arrays.sort(nums);
help(nums, target, res, ans, 0, 4);
return res;
}
private void help(int[] nums, int target, List<List<Integer>> res,
List<Integer> ans, int cur, int ksum) {
if (ans.size() == ksum) {
if (target == 0) res.add(new ArrayList<>(ans));
return;
}
for (int i = cur; i < nums.length; ++i) {
if (i > cur && nums[i] == nums[i - 1]) continue; // 去重
ans.add(nums[i]);
help(nums, target - nums[i], res, ans, i + 1, ksum);
ans.remove(ans.size() - 1);
}