mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 00:54:32 +08:00
Cleanup combination and combination test (#5902)
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.TreeSet;
|
||||
@ -13,8 +14,6 @@ public final class Combination {
|
||||
private Combination() {
|
||||
}
|
||||
|
||||
private static int length;
|
||||
|
||||
/**
|
||||
* Find all combinations of given array using backtracking
|
||||
* @param arr the array.
|
||||
@ -23,39 +22,45 @@ public final class Combination {
|
||||
* @return a list of all combinations of length n. If n == 0, return null.
|
||||
*/
|
||||
public static <T> List<TreeSet<T>> combination(T[] arr, int n) {
|
||||
if (n == 0) {
|
||||
return null;
|
||||
if (n < 0) {
|
||||
throw new IllegalArgumentException("The combination length cannot be negative.");
|
||||
}
|
||||
|
||||
if (n == 0) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
length = n;
|
||||
T[] array = arr.clone();
|
||||
Arrays.sort(array);
|
||||
|
||||
List<TreeSet<T>> result = new LinkedList<>();
|
||||
backtracking(array, 0, new TreeSet<T>(), result);
|
||||
backtracking(array, n, 0, new TreeSet<T>(), result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private static <T> void backtracking(T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) {
|
||||
if (index + length - currSet.size() > arr.length) {
|
||||
private static <T> void backtracking(T[] arr, int n, int index, TreeSet<T> currSet, List<TreeSet<T>> result) {
|
||||
if (index + n - currSet.size() > arr.length) {
|
||||
return;
|
||||
}
|
||||
if (length - 1 == currSet.size()) {
|
||||
if (currSet.size() == n - 1) {
|
||||
for (int i = index; i < arr.length; i++) {
|
||||
currSet.add(arr[i]);
|
||||
result.add((TreeSet<T>) currSet.clone());
|
||||
result.add(new TreeSet<>(currSet));
|
||||
currSet.remove(arr[i]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (int i = index; i < arr.length; i++) {
|
||||
currSet.add(arr[i]);
|
||||
backtracking(arr, i + 1, currSet, result);
|
||||
backtracking(arr, n, i + 1, currSet, result);
|
||||
currSet.remove(arr[i]);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user