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
| class Solution { public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { int count = 0; Map<Integer, Integer> sumToCountMap = new HashMap<>(); for (int a : nums1) { for (int b : nums2) { int target = -(a + b); count += sumToCountMap.computeIfAbsent(target, k -> sumCount(nums3, nums4, target)); } }
return count; }
private int sumCount(int[] nums3, int[] nums4, int target) { int count = 0; for (int c : nums3) { for (int d : nums4) { int sum = c + d; if (sum == target) { count++; } } } return count; } }
|
注意排序剪枝将错过同值元素的组合,如 nums3 = [0, 0, 1],nums4 = [-1, 1, 2],当 target = 1 时,如果执行到 0 + 2 > 1 进行了剪枝,则会错过 nums3 中第二个 0 与 nums4 中的元素可能组成的组合,所以不能执行此优化。
References
454. 4Sum II