Skip to content

Commit 37e2ffc

Browse files
committed
combinations
1 parent 029e01b commit 37e2ffc

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.LinkedList;
6+
import java.util.List;
7+
8+
// https://leetcode.com/problems/combinations/
9+
public class Combinations {
10+
11+
public static void main(String[] args) {
12+
Combinations obj = new Combinations();
13+
int n = 4;
14+
int k = 2;
15+
List<List<Integer>> resultList = obj.combineBaseOnFormular(n , k);
16+
System.out.println("resultList > " + Arrays.toString(resultList.toArray()));
17+
}
18+
19+
public List<List<Integer>> combine(int n, int k) {
20+
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
21+
if (n == 0 || k == 0) {
22+
return resultList;
23+
}
24+
25+
// dfs
26+
dfs(n, k, resultList, new ArrayList<Integer>(), 1);
27+
28+
return resultList;
29+
}
30+
31+
public void dfs(int n, int k, List<List<Integer>> resultList, List<Integer> list, int start) {
32+
if (k == 0) {
33+
resultList.add(new ArrayList<Integer>(list));
34+
return;
35+
}
36+
37+
for (int i = start; i <= n - k + 1; i++) {
38+
// [1, 2], [1, 3], [1, 4]
39+
// [2, 3], [2, 4]
40+
// [3, 4]
41+
list.add(i);
42+
dfs(n, k - 1, resultList, list, i + 1);
43+
list.remove(list.size() - 1);
44+
}
45+
}
46+
47+
// based on C(n,k)=C(n-1,k-1)+C(n-1,k)
48+
public List<List<Integer>> combineBaseOnFormular(int n, int k) {
49+
List<List<Integer>> resultList = new LinkedList<List<Integer>>();
50+
if (n < k || k == 0) {
51+
return resultList;
52+
}
53+
resultList = combineBaseOnFormular(n - 1, k - 1);
54+
// if at this point resultList is empty, it can only be that k - 1 == 0,
55+
// n - 1 < k - 1 is not possible since n >= k (if n < k, the function would have already returned at an early point)
56+
if (resultList.isEmpty()) {
57+
resultList.add(new LinkedList<Integer>());
58+
}
59+
for (List<Integer> list: resultList) {
60+
list.add(n);
61+
}
62+
63+
resultList.addAll(combineBaseOnFormular(n - 1, k));
64+
65+
return resultList;
66+
}
67+
}

0 commit comments

Comments
 (0)