-
Notifications
You must be signed in to change notification settings - Fork 457
/
Solution.java
56 lines (43 loc) · 1.53 KB
/
Solution.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
46
47
48
49
50
51
52
53
54
55
56
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
/// 77. Combinations
/// https://leetcode.com/problems/combinations/description/
/// 时间复杂度: O(n^k)
/// 空间复杂度: O(k)
public class Solution {
private ArrayList<List<Integer>> res;
public List<List<Integer>> combine(int n, int k) {
res = new ArrayList<List<Integer>>();
if(n <= 0 || k <= 0 || k > n)
return res;
LinkedList<Integer> c = new LinkedList<Integer>();
generateCombinations(n, k, 1, c);
return res;
}
// 求解C(n,k), 当前已经找到的组合存储在c中, 需要从start开始搜索新的元素
private void generateCombinations(int n, int k, int start, LinkedList<Integer> c){
if(c.size() == k){
res.add((List<Integer>)c.clone());
return;
}
// 还有k - c.size()个空位, 所以, [i...n] 中至少要有 k - c.size() 个元素
// i最多为 n - (k - c.size()) + 1
for(int i = start ; i <= n - (k - c.size()) + 1 ; i ++){
c.addLast(i);
generateCombinations(n, k, i + 1, c);
c.removeLast();
}
return;
}
private static void printList(List<Integer> list){
for(Integer e: list)
System.out.print(e + " ");
System.out.println();
}
public static void main(String[] args) {
List<List<Integer>> res = (new Solution()).combine(4, 2);
for(List<Integer> list: res)
printList(list);
}
}