LeetCode 18. 4Sum

Question

Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:

  • 0 <= a, b, c, d < n
  • a, b, c, and d are distinct.
  • nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

Example 1:

1
2
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:

1
2
Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]

Constraints:

  • 1 <= nums.length <= 200
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109

Source: https://leetcode.com/problems/4sum/

Solution

Time Complexity O(n^3). In fact, this is a DFS problem. Remember to draw the DFS tree.

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
// 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;
}

int sum = nums[left] + nums[right];
if (sum == target) {
result.add(new ArrayList<>(Arrays.asList(nums[left], nums[right])));
left++;
right--;
} else if (sum > target) {
right--;
} else {
left++;
}
}
return result;
}

// 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);
}
Author

Weihao Ye

Posted on

2022-03-10

Updated on

2022-03-10

Licensed under