Leetcode 77. 组合
解题思路
递归三部曲:递归函数的返回值以及参数;回溯函数终止条件;单层搜索的过程
代码
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> paths = new ArrayList<>();
private void backtracking(int n, int k, int startIndex) {
if (paths.size() == k) {
res.add(new ArrayList<>(paths));
return;
}
for (int i = startIndex; i <= n; i++){
paths.add(i);
backtracking(n, k, i + 1);
paths.remove(paths.size()-1);
}
}
public List<List<Integer>> combine(int n, int k) {
backtracking(n, k, 1);
return res;
}
}
//减枝
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> paths = new ArrayList<>();
private void backtracking(int n, int k, int startIndex) {
if (paths.size() == k) {
res.add(new ArrayList<>(paths));
return;
}
for (int i = startIndex; i <= n + 1 - (k - paths.size()); i++){
paths.add(i);
backtracking(n, k, i + 1);
paths.remove(paths.size()-1);
}
}
public List<List<Integer>> combine(int n, int k) {
backtracking(n, k, 1);
return res;
}
}
总结
减枝是在每次循环开始的减枝;如果剩下的元素个数无法满足达到k个则减枝