leetcode-zgd-day24-77.组合

49 阅读1分钟

77.组合

开始回溯法了!!!!

题目链接:77. 组合 - 力扣(LeetCode)

解题思路:

该题目中需要注意的点是:

1.ans.add(new ArrayList<>(path)); 这个new ArrayList<>()的操作是必须要做的,要创建一个新对象存进去。

2.对于剪枝,在for循环的结束条件处,需要注意思考

首先我们需要的数组组合长度为k,当前path中的长度为path.size(),那么还需要k-path.size()个元素。此题中i是可以取的到n的。所以至少从n-(k-path.size())+1这个位置开始,才可能让path达到指定长度。

3.startIndex的作用,startIndex是为了告诉下层函数,当前已经走到哪了,走过的就不要再走了。

 class Solution {
 ​
     List<List<Integer>> ans = new ArrayList<>();
     List<Integer> path = new LinkedList<>();
 ​
     public List<List<Integer>> combine(int n, int k) {
         combineHelper(n, k, 1);
         return ans;
     }
     public void combineHelper(int n, int k, int startIndex){
         // 结束条件
         if(path.size() == k){
             ans.add(new ArrayList<>(path));
             return;
         }
         for(int i = startIndex; i <= n - (k - path.size()) + 1; i++){
             path.add(i);
             combineHelper(n, k, i + 1);
             path.remove(path.size() - 1);
         }
     }
 }