77. Combinations
Tag BackTracing
Difficulty Medium
Link https://leetcode-cn.com/problems/combinations/
思路:
在一颗树上进行深度优先搜索,重视画图,这样可以使得思路更加清晰。
- 叶子结点的信息体现在从根结点到叶子结点的路径上,因此需要一个表示路径的变量 path,它是一个列表,特别地,path 是一个栈;
- 每一个结点递归地在做同样的事情,区别在于搜索起点,因此需要一个变量 start ,表示在区间 [begin, n] 里选出若干个数的组合;
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
Deque<Integer> path = new ArrayDeque<>();
dfs(n, k, 1, path, res);
return res;
}
public void dfs(int n, int k, int begin, Deque<Integer> path, List<List<Integer>> res) {
// 递归终止条件:取得k个数
if (path.size() == k) {
res.add(new ArrayList<>(path));
return;
}
for (int i = begin; i <= n; i++) {
path.add(i);
// 在路径上加入一个数以后从下一个数开始递归
dfs(n, k, i + 1, path, res);
// 退出递归需要去掉进入递归后选的数,即回溯
path.removeLast();
}
}
}
优化:分析上界进行剪枝
如果n=7, k=4
,那么从5开始的搜索就没有意义了,因为从5开始最多3个数,符合不了k=4
条件。
搜索起点的上界 + 接下来要搜索的元素个数 - 1 = n
搜索起点的上界 = n - (k - path.size()) + 1
那么只要将i <= n
换成i <= n - (k - path.size()) + 1
就可以了。