|
5 | 5 | import java.util.List;
|
6 | 6 | import java.util.TreeSet;
|
7 | 7 |
|
| 8 | + |
8 | 9 | /**
|
9 |
| - * Finds all permutations of given array |
| 10 | + * Finds all combinations of a given array that are a specific length by using backtracking. |
10 | 11 | * @author Alan Piao (<a href="https://github.com/cpiao3">git-Alan Piao</a>)
|
11 | 12 | */
|
12 |
| -public final class Combination { |
13 |
| - private Combination() { |
| 13 | +public final class CombinationGenerator { |
| 14 | + // Default private constructor to prevent instantiation |
| 15 | + |
| 16 | + private CombinationGenerator() { |
14 | 17 | }
|
15 | 18 |
|
16 |
| - private static int length; |
| 19 | + private static int length; //Define length outside all methods so that it can be accessed anywhere in the class. |
| 20 | + |
17 | 21 |
|
18 | 22 | /**
|
19 | 23 | * Find all combinations of given array using backtracking
|
20 |
| - * @param arr the array. |
21 |
| - * @param n length of combination |
| 24 | + * @param arr the array we want to find combinations of. |
| 25 | + * @param desiredLength the length of our desired combinations. |
22 | 26 | * @param <T> the type of elements in the array.
|
23 |
| - * @return a list of all combinations of length n. If n == 0, return null. |
| 27 | + * @return a list of all combinations of length desiredLength. If desiredLength is 0, return null. |
24 | 28 | */
|
25 |
| - public static <T> List<TreeSet<T>> combination(T[] arr, int n) { |
26 |
| - if (n == 0) { |
| 29 | + public static <T> List<TreeSet<T>> combination(T[] arr, int desiredLength) { |
| 30 | + if (desiredLength == 0) { |
27 | 31 | return null;
|
28 | 32 | }
|
29 |
| - length = n; |
| 33 | + length = desiredLength; |
30 | 34 | T[] array = arr.clone();
|
31 | 35 | Arrays.sort(array);
|
32 | 36 | List<TreeSet<T>> result = new LinkedList<>();
|
33 | 37 | backtracking(array, 0, new TreeSet<T>(), result);
|
34 | 38 | return result;
|
35 | 39 | }
|
36 | 40 |
|
| 41 | + |
37 | 42 | /**
|
38 | 43 | * Backtrack all possible combinations of a given array
|
39 |
| - * @param arr the array. |
| 44 | + * @param arr the array from earlier. |
40 | 45 | * @param index the starting index.
|
41 | 46 | * @param currSet set that tracks current combination
|
42 | 47 | * @param result the list contains all combination.
|
|
0 commit comments