定义
结合题目理解
力扣77题
题目链接:力扣
刚开始理解时,在代码角度究竟是怎样完成回溯过程困扰了很久
在师兄的帮助下打通了思路,在这里记录一下
首先在idea上跑一个完整的代码,借助结果进行理解
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
if (k <= 0 || n < k) {
return res;
}
Deque<Integer> path = new ArrayDeque<>();
dfs(n, k, 1, path, res);
return res;
}
private void dfs(int n, int k, int begin, Deque<Integer> path, List<List<Integer>> res) {
if (path.size() == k) {
res.add(new ArrayList<>(path));
return;
}
for (int i = begin; i <= n; i++) {
path.addLast(i);
System.out.println("递归之前 => " + path);
dfs(n, k, i + 1, path, res);
path.removeLast();
System.out.println("递归之后 => " + path);
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int n = 4;
int k = 2;
List<List<Integer>> res = solution.combine(n, k);
System.out.println(res);
}
}
递归之前 => [1]
递归之前 => [1, 2]
递归之后 => [1]
递归之前 => [1, 3]
递归之后 => [1]
递归之前 => [1, 4]
递归之后 => [1]
递归之后 => []
递归之前 => [2]
递归之前 => [2, 3]
递归之后 => [2]
递归之前 => [2, 4]
递归之后 => [2]
递归之后 => []
递归之前 => [3]
递归之前 => [3, 4]
递归之后 => [3]
递归之后 => []
递归之前 => [4]
递归之后 => []
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
贴图理解
反复操作这一段指令
begin=1;
i=1;
所以for循环中的i从1 开始
我的困扰是不知道他是怎么一步步退回来的,就是所谓的回溯
理解的话就是严格按照return结束当前的方法
但是这个只能退一个,从【1,2,3】--->【1,2】
之后for循环结束时,这个方法也会自动结束,dfs(i+1)也会结束,之后接着原来的函数继续执行即可
理解的关键点是;return可以结束当前的方法,可以结束上一层递归中调用的方法,按照图中理解