11package com .thealgorithms .backtracking ;
22
33import java .util .Arrays ;
4+ import java .util .Collections ;
45import java .util .LinkedList ;
56import java .util .List ;
67import java .util .TreeSet ;
@@ -13,8 +14,6 @@ public final class Combination {
1314 private Combination () {
1415 }
1516
16- private static int length ;
17-
1817 /**
1918 * Find all combinations of given array using backtracking
2019 * @param arr the array.
@@ -23,39 +22,45 @@ private Combination() {
2322 * @return a list of all combinations of length n. If n == 0, return null.
2423 */
2524 public static <T > List <TreeSet <T >> combination (T [] arr , int n ) {
25+ if (n < 0 ) {
26+ throw new IllegalArgumentException ("The combination length cannot be negative." );
27+ }
28+
2629 if (n == 0 ) {
27- return null ;
30+ return Collections . emptyList () ;
2831 }
29- length = n ;
3032 T [] array = arr .clone ();
3133 Arrays .sort (array );
34+
3235 List <TreeSet <T >> result = new LinkedList <>();
33- backtracking (array , 0 , new TreeSet <T >(), result );
36+ backtracking (array , n , 0 , new TreeSet <T >(), result );
3437 return result ;
3538 }
3639
3740 /**
3841 * Backtrack all possible combinations of a given array
3942 * @param arr the array.
43+ * @param n length of the combination
4044 * @param index the starting index.
4145 * @param currSet set that tracks current combination
4246 * @param result the list contains all combination.
4347 * @param <T> the type of elements in the array.
4448 */
45- private static <T > void backtracking (T [] arr , int index , TreeSet <T > currSet , List <TreeSet <T >> result ) {
46- if (index + length - currSet .size () > arr .length ) {
49+ private static <T > void backtracking (T [] arr , int n , int index , TreeSet <T > currSet , List <TreeSet <T >> result ) {
50+ if (index + n - currSet .size () > arr .length ) {
4751 return ;
4852 }
49- if (length - 1 == currSet .size ()) {
53+ if (currSet .size () == n - 1 ) {
5054 for (int i = index ; i < arr .length ; i ++) {
5155 currSet .add (arr [i ]);
52- result .add (( TreeSet <T >) currSet . clone ( ));
56+ result .add (new TreeSet <>( currSet ));
5357 currSet .remove (arr [i ]);
5458 }
59+ return ;
5560 }
5661 for (int i = index ; i < arr .length ; i ++) {
5762 currSet .add (arr [i ]);
58- backtracking (arr , i + 1 , currSet , result );
63+ backtracking (arr , n , i + 1 , currSet , result );
5964 currSet .remove (arr [i ]);
6065 }
6166 }
0 commit comments