解法一:排序+双指针

回溯法做四数之和超时,先来看一下三数之和。
参考官方题解:https://leetcode-cn.com/problems/3sum/solution/san-shu-zhi-he-by-leetcode-solution/

  1. import java.util.*;
  2. class Solution {
  3. public List<List<Integer>> threeSum(int[] nums) {
  4. final int target = 0;
  5. final int n = nums.length;
  6. List<List<Integer>> ans = new LinkedList<>();
  7. Arrays.sort(nums);
  8. for (int first = 0; first < n - 2; ) {
  9. int third = n - 1;
  10. for (int second = first + 1; (second < n - 1) && (second < third); ) {
  11. int sum = nums[first] + nums[second] + nums[third];
  12. while ((sum > target) && (second < third)) {
  13. sum -= nums[third];
  14. --third;
  15. sum += nums[third];
  16. }
  17. if (second >= third) {
  18. break;
  19. }
  20. if (sum == target) {
  21. List<Integer> list = new ArrayList<>();
  22. list.add(nums[first]);
  23. list.add(nums[second]);
  24. list.add(nums[third]);
  25. ans.add(list);
  26. }
  27. ++second;
  28. while ((nums[second] == nums[second - 1]) && (second < third)) {
  29. ++second;
  30. }
  31. }
  32. ++first;
  33. while ((nums[first] == nums[first - 1]) && (first < n - 2)) {
  34. ++first;
  35. }
  36. }
  37. return ans;
  38. }
  39. }