forked from algorithm008-class02/algorithm008-class02
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombine.java
More file actions
32 lines (24 loc) · 692 Bytes
/
Combine.java
File metadata and controls
32 lines (24 loc) · 692 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
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Combine {
private List<List<Integer>> res = new ArrayList<>();
private void findCombinations(int n, int k, int begin, Stack<Integer> pre) {
if (pre.size() == k) {
res.add(pre);
return;
}
for (int i = begin; i <= n; i++) {
pre.push(i);
findCombinations(n, k, i + 1, pre);
pre.pop();
}
}
public List<List<Integer>> combine(int n, int k) {
if (n < 0 || k < 0 || n < k) {
return res;
}
findCombinations(n, k, 1, new Stack<>());
return res;
}
}