-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcombinationSum2.java
More file actions
52 lines (49 loc) · 1.71 KB
/
combinationSum2.java
File metadata and controls
52 lines (49 loc) · 1.71 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
45
46
47
48
49
50
51
52
import java.util.*;
class Solution {
public List<List<Integer>> CombinationSum2(int[] arr, int n, int k) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(arr); // Sort the array to handle duplicates
backtrack(result, new ArrayList<>(), arr, k, 0);
return result;
}
private void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] arr, int remain, int start) {
if (remain == 0) {
result.add(new ArrayList<>(tempList));
return;
} else if (remain < 0) {
return;
} else {
for (int i = start; i < arr.length; i++) {
if (i > start && arr[i] == arr[i - 1]) continue; // skip duplicates
tempList.add(arr[i]);
backtrack(result, tempList, arr, remain - arr[i], i + 1);
tempList.remove(tempList.size() - 1);
}
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0) {
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
Solution solution = new Solution();
List<List<Integer>> ans = solution.CombinationSum2(a, n, k);
for (List<Integer> list : ans) {
for (int x : list) {
System.out.print(x + " ");
}
System.out.println();
}
if (ans.size() == 0) {
System.out.println();
}
}
}
}