三数之和
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);
int n=nums.length;
List<List<Integer>> res=new ArrayList<>();
for(int i=0;i<n;i++){
List<List<Integer>> sub=twoSumTarget(nums,i+1,target-nums[i]);
for(List<Integer> arr:sub){
arr.add(nums[i]);
res.add(arr);
}
while(i<n-1&&nums[i]==nums[i+1]) i++;
}
return res;
}
public List<List<Integer>> twoSumTarget(int[] nums,int start,int target){
int lo=start,hi=nums.length-1;
List<List<Integer>> res=new ArrayList<>();
while(lo<hi){
int sum = nums[lo] + nums[hi];
int left = nums[lo], right = nums[hi];
if (sum < target) {
while (lo < hi && nums[lo] == left) lo++;
} else if (sum > target) {
while (lo < hi && nums[hi] == right) hi--;
} else {
res.add(new ArrayList(Arrays.asList(left,right)));
while (lo < hi && nums[lo] == left) lo++;
while (lo < hi && nums[hi] == right) hi--;
}
}
return res;
}
}
n数之和
class Solution {
public List<List<Integer>> fourSum(int[] nums, long target) {
Arrays.sort(nums);
return nSumTarget(nums,4,0,target);
}
public List<List<Integer>> nSumTarget(int[] nums,int n,int start,long target){
int sz=nums.length;
List<List<Integer>> res=new ArrayList<>();
if (n < 2 || sz < n) return res;
if(n==2){
// 双指针那一套操作
int lo = start, hi = sz - 1;
while (lo < hi) {
int sum = nums[lo] + nums[hi];
int left = nums[lo], right = nums[hi];
if (sum < target) {
while (lo < hi && nums[lo] == left) lo++;
} else if (sum > target) {
while (lo < hi && nums[hi] == right) hi--;
} else {
res.add(new ArrayList(Arrays.asList(left,right)));
while (lo < hi && nums[lo] == left) lo++;
while (lo < hi && nums[hi] == right) hi--;
}
}
}else{
for(int i=start;i<sz;i++){
List<List<Integer>> sub=nSumTarget(nums,n-1,i+1,target-nums[i]);
for(List<Integer> arr:sub){
//(n-1)sum加上nums[i]即nsum
arr.add(nums[i]);
res.add(arr);
}
while(i<sz-1&&nums[i]==nums[i+1]) i++;
}
}
return res;
}
}