leetcode-18-java

问题:18. 4Sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

leetcode地址

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
public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<>();
if (null == nums || nums.length < 4) {
return list;
}

Arrays.sort(nums);

for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int threeTarget = target - nums[i];
threeSum(nums[i], threeTarget, i+1, nums, list);
}
return list;
}

public static void threeSum(int firt, int target, int left, int[] nums, List<List<Integer>> list) {

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

int twoTarget = target -nums[i];
twoSum(firt, nums[i], twoTarget, i + 1, nums.length - 1, nums, list);
}
}



private static void twoSum(int first, int second, int target, int left, int right, int[] nums, List<List<Integer>> list) {
while (left < right) {
int tmp = nums[left] + nums[right];
if (tmp == target) {
list.add(Arrays.asList(first, second, nums[left], nums[right]));
left ++;
right --;

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

while (left < right && nums[right] == nums[right + 1]) {
right --;
}
} else if (tmp > target) {
right --;
} else if (tmp < target) {
left ++;
}

}
}