[leetcode] problem 18 – 4sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note

The solution set must not contain duplicate quadruplets.

Example

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:

1
2
3
4
5
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

Code

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
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();

Arrays.sort(nums);

for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1])
continue;

threeSum(nums, target, nums[i], i + 1, result);
}

return result;

}

private void (int[] nums, int target, int num, int left, List<List<Integer>> result) {
for (int i = left; i < nums.length - 2; i++) {
if (i > left && nums[i] == nums[i - 1])
continue;

twoSum(nums, target, num, nums[i], i + 1, result);
}
}

private void twoSum(int[] nums, int target, int num1, int num2, int left, List<List<Integer>> result) {
int sum = target - num1 - num2;
int right = nums.length - 1;

while (left < right) {
if (nums[left] + nums[right] == sum) {
result.add(Arrays.asList(num1, num2, nums[left], nums[right]));
left++;
right--;

while (left < right && nums[left] == nums[left - 1])
left++;

while (left < right && nums[right] == nums[right + 1])
right--;
} else if (nums[left] + nums[right] < sum)
left++;
else
right--;
}
}