1 数组排序+双指针+递归调用(Java实现)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
return threeSumTarget(nums, 0);
}
public List<List<Integer>> threeSumTarget(int[] nums, int target){
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for(int i = 0; i < nums.length; i++){
List<List<Integer>> temps = twoSumTarget(nums, i + 1,target - nums[i]);
if(!temps.isEmpty()){
for(List<Integer> temp : temps){
temp.add(nums[i]);
res.add(temp);
}
while(i < nums.length - 1 && nums[i] == nums[i+1]) i++;
}
}
return res;
}
public List<List<Integer>> twoSumTarget(int[] nums, int start ,int target){
Arrays.sort(nums);
int low = start;
int high = nums.length - 1;
List<List<Integer>> res = new ArrayList<>();
while(low < high){
int left = nums[low];
int right = nums[high];
int sum = left + right;
if(sum < target){
while(low < high && nums[low] == left) low++;
}else if(sum > target){
while(low < high && nums[high] == right) high--;
}else if(sum == target){
res.add(new ArrayList<Integer>(Arrays.asList(left, right)));
while(low < high && nums[low] == left) low++;
while(low < high && nums[high] == right) high--;
}
}
return res;
}
}