|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.Arrays; |
| 3 | +import java.util.Comparator; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/* |
| 7 | + * @lc app=leetcode.cn id=15 lang=java |
| 8 | + * |
| 9 | + * [15] 三数之和 |
| 10 | + */ |
| 11 | + |
| 12 | +// @lc code=start |
| 13 | +class Solution { |
| 14 | + public List<List<Integer>> threeSum(int[] nums) { |
| 15 | + Arrays.sort(nums); |
| 16 | + return nSum(nums, 0, 3, 0); |
| 17 | + } |
| 18 | + |
| 19 | + private List<List<Integer>> nSum(int[] nums, int start, int n, int target) { |
| 20 | + List<List<Integer>> res = new ArrayList<>(); |
| 21 | + if (nums.length < n || n < 2) |
| 22 | + return res; |
| 23 | + |
| 24 | + if (n == 2) { |
| 25 | + int left = start; |
| 26 | + int right = nums.length - 1; |
| 27 | + while (left < right) { |
| 28 | + int sum = nums[left] + nums[right]; |
| 29 | + int low = nums[left]; |
| 30 | + int high = nums[right]; |
| 31 | + if (sum < target) { |
| 32 | + while (nums[left] == low && left < right) |
| 33 | + left++; |
| 34 | + } else if (sum > target) { |
| 35 | + while (nums[right] == high && left < right) |
| 36 | + right--; |
| 37 | + } else { |
| 38 | + List<Integer> rList = new ArrayList<>(); |
| 39 | + rList.add(nums[left]); |
| 40 | + rList.add(nums[right]); |
| 41 | + res.add(rList); |
| 42 | + while (nums[left] == low && left < right) |
| 43 | + left++; |
| 44 | + while (nums[right] == high && left < right) |
| 45 | + right--; |
| 46 | + } |
| 47 | + } |
| 48 | + } else { |
| 49 | + for (int i = start; i < nums.length; i++) { |
| 50 | + List<List<Integer>> result = nSum(nums, i + 1, n - 1, target - nums[i]); |
| 51 | + |
| 52 | + for (List<Integer> list : result) { |
| 53 | + list.add(0, nums[i]); |
| 54 | + res.add(list); |
| 55 | + } |
| 56 | + while (i < nums.length - 1 && nums[i] == nums[i + 1]) |
| 57 | + i++; |
| 58 | + } |
| 59 | + } |
| 60 | + return res; |
| 61 | + } |
| 62 | +} |
| 63 | +// @lc code=end |
0 commit comments