LeetCode 77. 组合
题目链接:https://leetcode.cn/problems/combinations/description/
文章链接:https://programmercarl.com/0077.%E7%BB%84%E5%90%88.html
思路
- 在这里要定义两个全局变量,一个用来存放符合条件单一结果,一个用来存放符合条件结果的集合。
- 函数里一定有两个参数,既然是集合n里面取k个数,那么n和k是两个int型的参数。然后还需要一个参数,为int型变量startIndex,这个参数用来记录本层递归的中,集合从哪里开始遍历
- path这个数组的大小如果达到k,说明我们找到了一个子集大小为k的组合了,在图中path存的就是根节点到叶子节点的路径。
- 回溯法的搜索过程就是一个树型结构的遍历过程,在如下图中,可以看出for循环用来横向遍历,递归的过程是纵向遍历。
private List<List<Integer>> result;
private LinkedList<Integer> path;
public List<List<Integer>> combine(int n, int k) {
result = new ArrayList<>();
path = new LinkedList<>();
backtracking(n, k, 0);
return result;
}
void backtracking(int n, int k, int startIndex) {
if (path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i <= n; i++) {
path.add(i);
backtracking(n, k, i + 1);
path.removeLast();
}
}