/*
方法一:使用回溯法暴力搜索
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> ret=new ArrayList<List<Integer>>();
List<Integer> list=new ArrayList<Integer>();
subsetsWithDup(nums,ret,list,target,0);
return ret;
}
public void subsetsWithDup(int[] ns,List<List<Integer>> ret,List<Integer> list,int target,int start) {
if(list.size()==4&&target==0){
ret.add(new ArrayList(list));
return;
}
if(list.size()==4) return;
for(int i=start;i<ns.length;i++){
if(i!=start&&ns[i]==ns[i-1]) continue;
list.add(ns[i]);
subsetsWithDup(ns,ret,list,target-ns[i],i+1);
list.remove(list.size()-1);
}
}
}
*/
/*
方法二:双指针
*/
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ret = new ArrayList<>();
Arrays.sort(nums);
int n = nums.length;
int start = 0;
for (int i = start; i < n-3; i++){
if (i > start && nums[i] == nums[i-1]){ // 确保i不重复
continue;
}
for (int j = i+1; j < n-2; j++){
if (j > (i+1) && nums[j] == nums[j-1]){ // 确保i不重复
continue;
}
int k = j+1;
int l = n-1;
while (k < l){
if (k > (j+1) && nums[k] == nums[k-1]){ // 确保k不重复
k++;
continue;
}
if (l < (n-1) && nums[l] == nums[l+1]){ // 确保l不重复
l--;
continue;
}
int s = nums[i] + nums[j] + nums[k] + nums[l];
if (s == target){
ret.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
k++;
l--;
} else if (s < target){
k++;
} else {
l--;
}
}
}
}
return ret;
}
}
leetcode第18题 四数之和 (双指针法+暴力搜索)
最新推荐文章于 2021-09-18 14:13:53 发布