理论基础
回溯法模板
返回值
终止条件
遍历过程
77 组合
1 2 3 4
【12 13 14
23 24
34】
k = 2:
for (int i = 1; i < size; i ++)
for (int j = i + 1; i < size; j ++)
k = 3:
for (int i = 1; i < size; i ++)
for (int j = i + 1; i < size; j ++)
for (int k = j + 1; k < size; k ++)
如果 n = 100, k = 50的话,我们就得写50层for循环,所以我们要别谋出路
回溯算法的树形结构:
回溯算法三部曲:
1.递归函数参数和返回值
2.确定终止条件
3.单层递归逻辑
题解
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
combineHelper(n, k, 1);
return result;
}
/**
* 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex
* @param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。
*/
private void combineHelper(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);
combineHelper(n, k, i + 1);
path.removeLast();
}
}
}
剪枝
n = 4, k = 4时,遍历到集合的第二个元素就已经不满足条件了
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
combineHelper(n, k, 1);
return result;
}
/**
* 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex
* @param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。
*/
private void combineHelper(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);
combineHelper(n, k, i + 1);
path.removeLast();
}
}
}