回溯算法
三部曲:
- 1.递归函数的参数和返回值 backTracking()
通常情况下返回值都是void
- 2.确定递归的终止条件
- 3.单层的递归逻辑
代码模版:
//一次的结果
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();
}
}