回溯算法–组合问题剪枝操作如何理解
package 回溯法;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* @author :lxin
* @date :Created 2023/11/30 19:18
* @description:回溯三部曲:
* 1.递归函数的参数和返回值
* 2.确定递归的终止条件
* 3.单层的递归逻辑
*/
public class 组合问题 {
public static LinkedList<Integer> path = new LinkedList<>();
public static List<List<Integer>> res = new ArrayList<>();
public static List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return res;
}
public static void backtracking(int n, int k,int startIndex){
if(path.size()==k){
res.add(path);
return;
}
for (int i = startIndex; i <=n-(k-path.size())+1; i++) {
path.add(i);
backtracking(n,k,i+1);
path.removeLast();
}
}
}
k-path.size
表示还需要选取的元素的个数,
n-(k-path.size)+1
表示还需要选取的元素至多从哪里开始搜索,
+1
表示可以从下标startIndex位置开始搜索。