回溯算法-减枝
题解:代码随想录 (programmercarl.com)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//结果
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combine(int n , int k){
backTracking(n,k,1);
return result;
}
//小集合
List<Integer> path = new ArrayList<>();
private void backTracking(int n, int k,int startNum) {
if(path.size() == k){
result.add(new ArrayList<>(path));
return;
}
for (int i = startNum;i <= n - (k - path.size()) + 1; i++) {
path.add(i);
backTracking(n,k ,i + 1);
path.remove(path.size() - 1);
}
}
|