-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinations.java
More file actions
67 lines (56 loc) · 1.78 KB
/
Combinations.java
File metadata and controls
67 lines (56 loc) · 1.78 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
67
package interview.recursion;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Combinations {
/**
* Generates all combinations and output them,
* selecting n elements from data.
*/
public void combinations(
List<Integer> selected, List<Integer> data, int n) {
if (n == 0) {
// output all selected elements
for (Integer i : selected) {
System.out.print(i);
System.out.print(" ");
}
System.out.println();
return;
}
if (data.isEmpty()) {
return;
}
// select element 0
selected.add(data.get(0));
combinations(selected, data.subList(1, data.size()), n - 1);
// un-select element 0
selected.remove(selected.size() - 1);
combinations(selected, data.subList(1, data.size()), n);
}
public static void main(String[] args) {
Combinations comb = new Combinations();
System.out.println("Testing normal data.");
comb.combinations(
new ArrayList<>(), Arrays.asList(1, 2, 3, 4), 2);
System.out.println("==========");
System.out.println("Testing empty source data.");
comb.combinations(
new ArrayList<>(), new ArrayList<>(), 2);
System.out.println("==========");
comb.combinations(
new ArrayList<>(), new ArrayList<>(), 0);
System.out.println("==========");
System.out.println("Selecting 1 and 0 elements.");
comb.combinations(
new ArrayList<>(), Arrays.asList(1, 2, 3, 4), 1);
System.out.println("==========");
comb.combinations(
new ArrayList<>(), Arrays.asList(1, 2, 3, 4), 0);
System.out.println("==========");
System.out.println("Testing large data");
comb.combinations(
new ArrayList<>(),
Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 4);
}
}