1
1
package com .thealgorithms .backtracking ;
2
2
3
3
import java .util .Arrays ;
4
+ import java .util .Collections ;
4
5
import java .util .LinkedList ;
5
6
import java .util .List ;
6
7
import java .util .TreeSet ;
@@ -13,8 +14,6 @@ public final class Combination {
13
14
private Combination () {
14
15
}
15
16
16
- private static int length ;
17
-
18
17
/**
19
18
* Find all combinations of given array using backtracking
20
19
* @param arr the array.
@@ -23,39 +22,45 @@ private Combination() {
23
22
* @return a list of all combinations of length n. If n == 0, return null.
24
23
*/
25
24
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
+
26
29
if (n == 0 ) {
27
- return null ;
30
+ return Collections . emptyList () ;
28
31
}
29
- length = n ;
30
32
T [] array = arr .clone ();
31
33
Arrays .sort (array );
34
+
32
35
List <TreeSet <T >> result = new LinkedList <>();
33
- backtracking (array , 0 , new TreeSet <T >(), result );
36
+ backtracking (array , n , 0 , new TreeSet <T >(), result );
34
37
return result ;
35
38
}
36
39
37
40
/**
38
41
* Backtrack all possible combinations of a given array
39
42
* @param arr the array.
43
+ * @param n length of the combination
40
44
* @param index the starting index.
41
45
* @param currSet set that tracks current combination
42
46
* @param result the list contains all combination.
43
47
* @param <T> the type of elements in the array.
44
48
*/
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 ) {
47
51
return ;
48
52
}
49
- if (length - 1 == currSet .size ()) {
53
+ if (currSet .size () == n - 1 ) {
50
54
for (int i = index ; i < arr .length ; i ++) {
51
55
currSet .add (arr [i ]);
52
- result .add (( TreeSet <T >) currSet . clone ( ));
56
+ result .add (new TreeSet <>( currSet ));
53
57
currSet .remove (arr [i ]);
54
58
}
59
+ return ;
55
60
}
56
61
for (int i = index ; i < arr .length ; i ++) {
57
62
currSet .add (arr [i ]);
58
- backtracking (arr , i + 1 , currSet , result );
63
+ backtracking (arr , n , i + 1 , currSet , result );
59
64
currSet .remove (arr [i ]);
60
65
}
61
66
}
0 commit comments