-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
Combination.java
45 lines (38 loc) · 852 Bytes
/
Combination.java
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
package problems.medium;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sherxon on 6/3/17.
*/
public class Combination {
private static void exec(List<List<Integer>> list, boolean[] b, int k, int i) {
if (k < 0) {
return;
}
if (k == 0) {
List<Integer> l = new ArrayList<>();
for (int j = 1; j < b.length; j++) {
if (b[j]) {
l.add(j);
}
}
list.add(l);
}
for (int j = i; j < b.length; j++) {
if (!b[j]) {
b[j] = true;
exec(list, b, k - 1, j);
b[j] = false;
}
}
}
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> list = new ArrayList<>();
if (k <= 0 || k > n) {
return list;
}
boolean[] b = new boolean[n + 1];
exec(list, b, k, 1);
return list;
}
}