题目:力扣
解题思路:
一、回溯法,但效率比较低,超时了
回溯法的难点在于剪枝,首先对数组进行一个排序,在同一级选择的时候不选择重复的元素。
二、双指针
固定住前两个,后两个使用双指针的方法寻找
//回溯法模板
void backtrack(选择列表, 路径){
if 满足结束的条件:
result.add(路径)
return
for 选择 in 选择列表:
做选择
backtrack(路径,选择列表)
撤销选择
}
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> fourSum(int[] nums, int target) {
if(nums.length == 0){
return res;
}
List<Integer> route = new LinkedList<Integer>();
//关键
Arrays.sort(nums);
backtarce(nums,0 , route, target);
return res;
}
public void backtarce(int[] nums, int index, List<Integer> route, int target){
if(route.size()== 4 && target == 0){
res.add(new LinkedList<Integer>(route));
return;
}
for(int i = index; i < nums.length; i++){
if(i>index && nums[i] == nums[i-1]){
continue;
}
else{
route.add(nums[i]);
backtarce(nums, i+1, route, target-nums[i]);
route.remove(route.size()-1);
}
}
}
}
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> fourSum(int[] nums, int target) {
if(nums.length == 0){
return res;
}
Arrays.sort(nums);
for(int first = 0; first < nums.length-3; first++){
if(first>0 && nums[first] == nums[first-1]){
continue;
}
for(int second = first+1; second < nums.length-2;second++){
if(second > first+1 && nums[second] == nums[second-1]){
continue;
}
int remain = target - nums[second]-nums[first];
int third = second+1;
int forth = nums.length-1;
while(third < forth){
while(third > second+1 && third < forth && nums[third] == nums[third-1]){
third++;
}
// while(forth < nums.length-1 && nums[forth] == nums[forth+1]){
// forth--;
// }
if(third >= forth){
break;
}
int sum = nums[third]+nums[forth];
if(sum == remain){
ArrayList<Integer> route = new ArrayList<>();
route.add(nums[first]);
route.add(nums[second]);
route.add(nums[third]);
route.add(nums[forth]);
res.add(route);
forth--;
third++;
}
else if(sum < remain){
third++;
}
else{
forth--;
}
}
}
}
return res;
}
}