-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsum_4.java
More file actions
44 lines (39 loc) · 1.43 KB
/
sum_4.java
File metadata and controls
44 lines (39 loc) · 1.43 KB
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
import java.util.*;
public class sum_4 {
public static List<List<Integer>> fourSum(int[] nums, int target) {
int n = nums.length;
Set<List<Integer>> set = new HashSet<>();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
for (int l = k + 1; l < n; l++) {
long sum = (long)nums[i] + nums[j];
sum += nums[k];
sum += nums[l];
if (sum == target) {
List<Integer> temp = Arrays.asList(nums[i], nums[j], nums[k], nums[l]);
Collections.sort(temp);
set.add(temp);
}
}
}
}
}
List<List<Integer>> ans = new ArrayList<>(set);
return ans;
}
public static void main(String[] args) {
int[] nums = {4, 3, 3, 4, 4, 2, 1, 2, 1, 1};
int target = 9;
List<List<Integer>> ans = fourSum(nums, target);
System.out.println("The quadruplets are: ");
for (List<Integer> it : ans) {
System.out.print("[");
for (int ele : it) {
System.out.print(ele + " ");
}
System.out.print("] ");
}
System.out.println();
}
}