理论基础
回溯法:
- 回溯是一种搜索方式。
- 回溯是递归的副产品,有递归就必有回溯。
- 回溯本质是穷举,偶尔有剪枝来提高效率。
- 回溯解决的问题都可以抽象为树形结构(n叉树,有终止条件)。
- 回溯法解决的都是在集合中递归查找子集,集合的大小就构成了树的宽度,递归的深度就构成了树的深度。
回溯模版:
void backtracking(参数) {
if (终止条件) {
存放结果;
return;
}
for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {
处理节点;
backtracking(路径,选择列表); // 递归
回溯,撤销处理结果
}
}
77. 组合
题目链接:https://leetcode.com/problems/combinations
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. You may return the answer in any order.
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
思路:
- 多层嵌套for循环
但是n=50,k=100就无法表示 - 树形结构图
n相当于树的宽度,k相当于树的深度 - why new ArrayList<>(path)?
The new ArrayList<>(path) statement creates a new ArrayList object and initializes it with the elements of the path list.
The reason for creating a new ArrayList is to ensure that the current state of the path list is captured and stored in the result list. If we were to directly add the reference to the path list, any subsequent modifications to the path list would affect the combinations stored in the result list.
回溯法:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n, k, 1); //注意从1,【1:n】
return result;
}
private void backtracking(int n, int k, int startIndex) {
if (path.size() == k) { //终止条件
result.add(new ArrayList<>(path)); // why new?
return;
}
for (int i = startIndex; i <= n; i++) { // 横向遍历
path.add(i);
backtracking(n, k, i+1); //纵向,从i+1开始
path.remove(path.size()-1); // path.removeLast();
}
}
}
剪枝优化:
- 已经选择的元素个数:path.size();
- 需要的元素个数为: k - path.size();
- 列表中剩余元素(n-i) >= 所需需要的元素个数(k - path.size())
- 在集合n中至多要从该起始位置 : i <= n - (k - path.size()) + 1,开始遍历
如果for循环选择的起始位置之后的元素个数 已经不足 我们需要的元素个数了,那么就没有必要搜索了
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
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++) { //剪枝操作,至多开始位置
path.add(i);
backtracking(n, k, i+1);
path.remove(path.size()-1);
}
}
}