// two pointer search, take advantage of the orderliness of nums // @pre: nums is sorted private List<List<Integer>> twoSum(int[] nums, int target, int start) { List<List<Integer>> result = new ArrayList<>(); int left = start; int right = nums.length - 1; while (left < right) { // a better way to skip duplicates // can perform skipping even if sum != 0 if (left > start && nums[left] == nums[left - 1]) { left++; continue; } if (right < nums.length - 1 && nums[right] == nums[right + 1]) { right--; continue; }
// dfs, depth is k // @pre: nums is sorted // return the k-sum combinations with given k private List<List<Integer>> kSum(int[] nums, int k, int target, int start) { List<List<Integer>> result = new ArrayList<>(); if (start >= nums.length) { return result; } // pruning double avg = ((double) target) / k; if (nums[start] > avg || nums[nums.length - 1] < avg) { return result; } if (k == 2) { return twoSum(nums, target, start); } for (int i = start; i < nums.length; i++) { // skip duplicates if (i != start && nums[i] == nums[i - 1]) { continue; } int n = nums[i]; for (List<Integer> subset : kSum(nums, k - 1, target - n, i + 1)) { List<Integer> currLayerComb = new ArrayList<>(); currLayerComb.add(n); currLayerComb.addAll(subset); result.add(currLayerComb); } } return result; }
public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); return kSum(nums, 4, target, 0); }