Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathCombination.java
More file actions
Latest commit
66 lines (60 loc) · 2.12 KB
/
Copy pathCombination.java
File metadata and controls
66 lines (60 loc) · 2.12 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
packagecom.thealgorithms.backtracking;
importjava.util.Arrays;
importjava.util.Collections;
importjava.util.LinkedList;
importjava.util.List;
importjava.util.TreeSet;
/**
* Finds all combinations of a given array using backtracking algorithm * @author Alan Piao (<a href="https://github.com/cpiao3">git-Alan Piao</a>)
*/
publicfinalclassCombination {
privateCombination() {
}
/**
* Find all combinations of given array using backtracking
* @param arr the array.
* @param n length of combination
* @param <T> the type of elements in the array.
* @return a list of all combinations of length n. If n == 0, return null.
*/
publicstatic <T> List<TreeSet<T>> combination(T[] arr, intn) {
if (n < 0) {
thrownewIllegalArgumentException("The combination length cannot be negative.");
}
if (n == 0) {
returnCollections.emptyList();
}
T[] array = arr.clone();
Arrays.sort(array);
List<TreeSet<T>> result = newLinkedList<>();
backtracking(array, n, 0, newTreeSet<T>(), result);
returnresult;
}
/**
* Backtrack all possible combinations of a given array
* @param arr the array.
* @param n length of the combination
* @param index the starting index.
* @param currSet set that tracks current combination
* @param result the list contains all combination.
* @param <T> the type of elements in the array.
*/
privatestatic <T> voidbacktracking(T[] arr, intn, intindex, TreeSet<T> currSet, List<TreeSet<T>> result) {
if (index + n - currSet.size() > arr.length) {
return;
}
if (currSet.size() == n - 1) {
for (inti = index; i < arr.length; i++) {
currSet.add(arr[i]);
result.add(newTreeSet<>(currSet));
currSet.remove(arr[i]);
}
return;
}
for (inti = index; i < arr.length; i++) {
currSet.add(arr[i]);
backtracking(arr, n, i + 1, currSet, result);
currSet.remove(arr[i]);
}
}
}