首页 > 编程语言 >代码随想录——回溯算法

代码随想录——回溯算法

时间:2022-12-31 11:45:57浏览次数:55  
标签:int 随想录 startIndex 算法 result 回溯 new path

组合

题目 中等

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> combine(int n, int k) {
        combineHelper(n, k, 1);
        return result;
    }

    /**
     * 每次从集合中选取元素,可选择的范围随着选择的进行而收缩,调整可选择的范围,就是要靠startIndex
     * @param startIndex 用来记录本层递归的中,集合从哪里开始遍历(集合就是[1,...,n] )。
     */
    private void combineHelper(int n, int k, int startIndex){
        //终止条件
        if (path.size() == k){
            result.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.removeLast();
        }
    }
}

 

标签:int,随想录,startIndex,算法,result,回溯,new,path
From: https://www.cnblogs.com/CWZhou/p/17016379.html

相关文章