不解释了,直接上代码,代码详细注释。
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> res = new LinkedList<>();
for(int i = 0; i < nums.length; ++i){
List<List<Integer>> tmp = threeSum(nums, i + 1, target - nums[i]);
for(List<Integer> tuple : tmp){
tuple.add(nums[i]);
res.add(tuple);
}
while(i < nums.length - 1 && nums[i] == nums[i + 1]) i++;
}
return res;
}
public List<List<Integer>> threeSum(int[] nums, int start, int target) {
List<List<Integer>> res = new LinkedList<>();
for(int i = start; i < nums.length; ++i){
List<List<Integer>> tmp = twoSum(nums, i + 1, target - nums[i]);
for(List<Integer> tuple : tmp){
tuple.add(nums[i]);
res.add(tuple);
}
while(i < nums.length - 1 && nums[i] == nums[i + 1]) i++;
}
return res;
}
public List<List<Integer>> twoSum(int[] nums, int start,int target){
int lo = start;
int rh = nums.length - 1;
List<List<Integer>> res = new LinkedList<>();
while(lo < rh){
int left = nums[lo];
int right = nums[rh];
int sum = nums[lo] + nums[rh];
if(sum < target){
while(lo < rh && nums[lo] == left) lo ++;
}else if(sum > target){
while(lo < rh && nums[rh] == right) rh --;
}else{
List<Integer> tmp = new LinkedList<>();
tmp.add(left);
tmp.add(right);
res.add(tmp);
while(lo < rh && nums[lo] == left) lo ++;
while(lo < rh && nums[rh] == right) rh --;
}
}
return res;
}
}
|