77. 组合
题解与想法
回溯算法
回溯三步曲
- 递归函数的返回值以及参数
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++){
//i <= n 剪枝为 n - (k - path.size()) + 1
path.add(i);
backtracking(n, k, i + 1);
path.removeLast();
}
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return result;
}
private 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++){ //i <= n 剪枝为 n - (k - path.size()) + 1
path.add(i);
backtracking(n, k, i + 1);
path.removeLast();
}
}
}