回溯法解决的问题都可以抽象为树形结构。
回溯法解决的都是在集合中递归查找子集,集合的大小就构成了树的宽度,递归的深度,都构成的树的深度。
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
n相当于树的宽度,k相当于树的深度.
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;
}
//startIndex来记录下一层递归,搜索的起始位置。
public void backtracking(int n, int k, int startindex){
//每次搜索到了叶子节点,我们就找到了一个结果。
if(path.size() == k){
//这里需要注意添加的时候必须创建一个新的列表,直接添加path会出错
result.add(new ArrayList<Integer>(path));
return;
}
for(int i = startindex; i <= n; i++){
path.add(i);
backtracking(n, k, i + 1);
path.remove(path.size() - 1);
}
}
}
可以剪枝的地方就在递归中每一层的for循环所选择的起始位置。
如果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;
}
public void backtracking(int n, int k, int startindex){
if(path.size() == k){
result.add(new ArrayList<Integer>(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);
}
}
}
找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:
只使用数字1到9
每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int sum = 0;
public List<List<Integer>> combinationSum3(int k, int n) {
backtracing(k, n, 1);
return result;
}
public void backtracing(int k, int n, int startindex){
if(path.size() == k){
if(sum == n){
result.add(new ArrayList<>(path));
return;
}
}
for(int i = startindex; i <= 9; i++){
path.add(i);
sum += i;
backtracing(k ,n, i + 1);
sum -= i;
path.remove(path.size() - 1);
}
}
}
已选元素总和如果已经大于n了,那么往后遍历就没有意义了,直接剪掉。
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int sum = 0;
public List<List<Integer>> combinationSum3(int k, int n) {
backtracing(k, n, 1);
return result;
}
public void backtracing(int k, int n, int startindex){
if(path.size() == k){
if(sum == n){
result.add(new ArrayList<>(path));
return;
}
}
//减枝 9 - (k - path.size()) + 1
for(int i = startindex; i <= 9 - (k - path.size()) + 1; i++){
path.add(i);
sum += i;
if(sum > n){
sum -= i;
path.remove(path.size() - 1);
return;
}
backtracing(k ,n, i + 1);
sum -= i;
path.remove(path.size() - 1);
}
}
}