解法一:排序+双指针
回溯法做四数之和超时,先来看一下三数之和。
参考官方题解:https://leetcode-cn.com/problems/3sum/solution/san-shu-zhi-he-by-leetcode-solution/
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
final int target = 0;
final int n = nums.length;
List<List<Integer>> ans = new LinkedList<>();
Arrays.sort(nums);
for (int first = 0; first < n - 2; ) {
int third = n - 1;
for (int second = first + 1; (second < n - 1) && (second < third); ) {
int sum = nums[first] + nums[second] + nums[third];
while ((sum > target) && (second < third)) {
sum -= nums[third];
--third;
sum += nums[third];
}
if (second >= third) {
break;
}
if (sum == target) {
List<Integer> list = new ArrayList<>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
ans.add(list);
}
++second;
while ((nums[second] == nums[second - 1]) && (second < third)) {
++second;
}
}
++first;
while ((nums[first] == nums[first - 1]) && (first < n - 2)) {
++first;
}
}
return ans;
}
}