Leetcode.18 4Sum
Leetcode.18 4Sum
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]
]
Solution
可以由ksum依次递归到2sum
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
if(nums.length < 4){
return new ArrayList<>();
}
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
int l = 0;
while(l<nums.length-3){
//l-1已经实现过所有的方式,所以l不循环
if(l>0&&nums[l] == nums[l-1]){
l++;
continue;
}
int m = l+1;
//3 sum
while(m<nums.length-2){
if(m>l+1&&nums[m] == nums[m-1]){
m++;
continue;
}
int sum = target-nums[l]-nums[m];
int n = m+1;
int p = nums.length-1;
//2 sum
while(n<p){
if(nums[n]+nums[p] == sum){
res.add(Arrays.asList(nums[l],nums[m],nums[n],nums[p]));
while(n<p && nums[n] == nums[n+1]){
n++;
}
while(n<p && nums[p] == nums[p-1]){
p--;
};
n++;
p--;
}else if(nums[n]+nums[p]>sum){
p--;
}else{
n++;
}
}
m++;
}
l++;
}
return res;
}
}
爱生活、爱编程