题目

image.png

代码

  1. class Solution {
  2. List< List<Integer> > result = new ArrayList<>();
  3. LinkedList<Integer> path = new LinkedList<>();
  4. public List<List<Integer>> combine(int n, int k) {
  5. backtracking(n,k,1);
  6. return result;
  7. }
  8. /**
  9. * n 元素总个数
  10. * k k个元素一组
  11. * startIndex 这个参数⽤来记录本层递归的中,集合从哪⾥开始遍历
  12. */
  13. public void backtracking(int n, int k, int startIndex) {
  14. int size = path.size();
  15. if(size == k) {
  16. result.add(new ArrayList<>(path));
  17. return ;
  18. }
  19. //剪枝操作
  20. //在集合n中⾄多要从该起始位置 : n - (k - path.size()) + 1,开始遍历
  21. //为什么有个+1呢,因为包括起始位置,我们要是⼀个左闭的集合
  22. for(int i = startIndex; i <= n - ( k - size ) + 1; i++ ) {
  23. path.add(i);
  24. backtracking(n,k,i+1);
  25. path.removeLast();
  26. }
  27. }
  28. }