我新建的个人博客,欢迎访问:hmilzy.github.io


第77题. 组合

题目链接: 组合

回溯 + 剪枝
可以参考这个题解,写的是真好。

题解

剪枝前:25.78%

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

class Solution {

List<Integer> path = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();

public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return result;
}

public void backtracking(int n,int k,int startIndex) {
if(path.size() == k) {
result.add(new ArrayList<>(path));
return;
}

for(int i = startIndex; i <= n; i++) {
path.add(i);
backtracking(n,k,i + 1);
path.remove(path.size() - 1);
}
}
}


剪枝过后:99.97%

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

class Solution {

List<Integer> path = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();

public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return result;
}

public void backtracking(int n,int k,int startIndex) {
if(path.size() == k) {
result.add(new ArrayList<>(path));
return;
}

for(int i = startIndex; i <= n - (k - path.size()) + 1; i++) {
path.add(i);
backtracking(n,k,i + 1);
path.remove(path.size() - 1);
}
}
}