-
Notifications
You must be signed in to change notification settings - Fork 87
/
FourSum.java
47 lines (47 loc) · 1.85 KB
/
FourSum.java
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
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
return kSum(nums, target, 0, 4);
}
public List<List<Integer>> kSum(int[] nums, long target, int start, int k) {
List<List<Integer>> res = new ArrayList<>();
// If we have run out of numbers to add, return res.
if (start == nums.length) {
return res;
}
// There are k remaining values to add to the sum. The
// average of these values is at least target / k.
long average_value = target / k;
// We cannot obtain a sum of target if the smallest value
// in nums is greater than target / k or if the largest
// value in nums is smaller than target / k.
if (nums[start] > average_value || average_value > nums[nums.length - 1]) {
return res;
}
if (k == 2) {
return twoSum(nums, target, start);
}
for (int i = start; i < nums.length; ++i) {
if (i == start || nums[i - 1] != nums[i]) {
for (List<Integer> subset : kSum(nums, target - nums[i], i + 1, k - 1)) {
res.add(new ArrayList<>(Arrays.asList(nums[i])));
res.get(res.size() - 1).addAll(subset);
}
}
}
return res;
}
public List<List<Integer>> twoSum(int[] nums, long target, int start) {
List<List<Integer>> res = new ArrayList<>();
Set<Long> s = new HashSet<>();
for (int i = start; i < nums.length; ++i) {
if (res.isEmpty() || res.get(res.size() - 1).get(1) != nums[i]) {
if (s.contains(target - nums[i])) {
res.add(Arrays.asList((int)target - nums[i], nums[i]));
}
}
s.add((long)nums[i]);
}
return res;
}
}