forked from algorithm019/algorithm019
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombine.java
More file actions
43 lines (31 loc) · 814 Bytes
/
Combine.java
File metadata and controls
43 lines (31 loc) · 814 Bytes
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
import java.util.ArrayList;
import java.util.List;
/**
* Description: 组合
* Date: 2020-11-20
* Time: 10:10 PM
*/
public class Combine {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
//terminator
if (n <= 0 || n < k || k == 0) {
return res;
}
//process
//if choose the n'th num
res = combine(n - 1, k - 1);
if (res.isEmpty()) {
res.add(new ArrayList<>());
}
for (List<Integer> list : res) {
list.add(n);
}
//if not choose the n'th num
res.addAll(combine(n - 1, k));
return res;
}
public static void main(String[] args) {
System.out.println(new Combine().combine(6, 2));
}
}