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:
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 List<List<Integer>> fourSum(int[] nums, int target) {
if (nums == null || nums.length < 4) {
return new ArrayList<List<Integer>>();
}
Arrays.sort(nums);
Set<List<Integer>> set = new HashSet<List<Integer>>();
// 和3Sum一样,只是多了一个循环
for (int a = 0; a < nums.length - 3; a++) {
int target_3Sum = target - nums[a];
for (int b = a + 1; b < nums.length - 2; b++) {
int c = b + 1, d = nums.length - 1;
while (c < d) {
int sum = nums[b] + nums[c] + nums[d];
if (sum == target_3Sum) {
// 将结果加入集合
List<Integer> tmp = new ArrayList<Integer>();
tmp.add(nums[a]);
tmp.add(nums[b]);
tmp.add(nums[c]);
tmp.add(nums[d]);
set.add(tmp);
// 去重
while (++c < d && nums[c - 1] == nums[c])
;
while (--d > c && nums[d + 1] == nums[d])
;
}
else if (sum < target_3Sum) {
c++;
} else {
d--;
}
}
}
}
return new ArrayList<List<Integer>>(set);
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。