-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinations.java
More file actions
34 lines (31 loc) · 877 Bytes
/
Combinations.java
File metadata and controls
34 lines (31 loc) · 877 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
package questions100;
import java.util.*;
public class Combinations {
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
// Start typing your Java solution below
// DO NOT write main() function
if (k == 0) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
return result;
}
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> last = combine(n, k - 1);
if (last.isEmpty()) {
for (int i = 1; i <= n; i++) {
ArrayList<Integer> l = new ArrayList<Integer>();
l.add(i);
result.add(l);
}
} else {
for (ArrayList<Integer> list : last) {
for (int i = list.get(list.size() - 1) + 1; i <= n; i++) {
ArrayList<Integer> l = new ArrayList<Integer>();
l.addAll(list);
l.add(i);
result.add(l);
}
}
}
return result;
}
}