1. public class Solution {
  2. LinkedList<Integer> path = new LinkedList<Integer>(); // 用来存放符合条件单一结果
  3. List<List<Integer>> result = new ArrayList<List<Integer>>(); // 存放符合条件结果的集合
  4. public List<List<Integer>> combine(int n, int k) {
  5. if (k <= 0 || n < k) {
  6. return result;
  7. }
  8. backtracking(n, k, 1);
  9. return result;
  10. }
  11. public void backtracking(int n, int k, int startIndex) {
  12. // 递归终止条件是:path 的长度等于 k
  13. if (path.size() == k) {
  14. result.add(new LinkedList<Integer>(path));
  15. return;
  16. }
  17. // 遍历可能的搜索起点
  18. for (int i = startIndex; i <= n; i++) { // 控制树的横向遍历
  19. // 向路径变量里添加一个数
  20. path.addLast(i);
  21. // 递归:控制树的纵向遍历
  22. backtracking(n, k, i + 1);
  23. // 回溯
  24. path.removeLast();
  25. }
  26. }
  27. }

来举一个例子,n = 4k = 4的话,那么第一层for循环的时候,从元素2开始的遍历都没有意义了。在第二层for循环,从元素3开始的遍历都没有意义了
leetcode-77:组合 剪枝 - 图1
所以,可以剪枝的地方就在递归中每一层的**for**循环所选择的起始位置
如果**for**循环选择的起始位置之后的元素个数已经不足我们需要的元素个数了,那么就没有必要搜索了

优化过程

  • 已经选择的元素个数:path.size();
  • 还需要的元素个数为: k - path.size();
  • 在集合n中至多要从该起始位置 : n - (k - path.size()) + 1,开始遍历

举个例子,n = 4k = 3, 目前已经选取的元素为0n - (k - 0) + 14 - ( 3 - 0) + 1 = 2
2开始搜索都是合理的,可以是组合[2, 3, 4]

  1. for(int i = startIndex; i <= n - (k - path.size()) + 1; i++)