1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| public class A15Sum3 {
public static List<List<Integer>> sum3(int[] nums, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if (nums.length < 3) { return result; } Arrays.sort(nums); for (int i = 0; i < nums.length; i++) { int start = i + 1, end = nums.length - 1; int tmp = target - nums[i]; if (i > 0 && nums[i] == nums[i - 1]) { continue; } while (start < end) { if (tmp < nums[start] + nums[end]) { end--; } else if (tmp > nums[start] + nums[end]) { start++; } else { List<Integer> tmp2 = new ArrayList<Integer>(); tmp2.add(nums[i]); tmp2.add(nums[start]); tmp2.add(nums[end]); start++; end--; while (start < end && nums[start] == nums[start - 1]) { start++; } while (end > start && nums[end] == nums[end + 1]) { end--; } result.add(tmp2); } }
} return result; }
public static List<List<Integer>> sum3New(int[] nums, int target) { Map<List<Integer>, List<Integer>> result = new HashMap<>(); Arrays.sort(nums); sum3Backtracking(result, new ArrayList<Integer>(), nums, target, 0); return new ArrayList<>(result.values()); }
public static void sum3Backtracking(Map<List<Integer>, List<Integer>> result, List<Integer> item, int[] nums, int remain, int start) { if (nums.length> 0 && remain < minArraySum(nums)) { return; } else if (remain == 0 && item.size() == 3) { result.put(new ArrayList<>(item), new ArrayList<>(item)); } else { for (int i = start; i < nums.length; i++) { item.add(nums[i]); sum3Backtracking(result, item, nums, remain - nums[i], i + 1); item.remove(item.size() - 1); } } }
private static int minArraySum(int[] nums) { int start = 0; if (start >= nums.length) { return Integer.MAX_VALUE; } if (nums[start] >= 0) { return nums[start]; } else { int min = 0; for (int i = start; i < nums.length; i++) { if (nums[i] < 0 && i < 4) { min += nums[i]; } } return min; } }
public static void main(String[] args) { System.out.println(sum3(new int[]{0, 0, 0, 0, 0, 0}, 0)); System.out.println(sum3New(new int[]{0, 0, 0, 0, 0, 0}, 0)); System.out.println(sum3(new int[]{-2, -1, 0, 1, 2, 3}, 0)); System.out.println(sum3New(new int[]{-2, -1, 0, 1, 2, 3}, 0)); } }
|