组合

72 阅读1分钟

77 组合

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;
    }
    private void combineHelper(int n, int k, int startIndex) {
        //终止条件,当单个结果的大小等于k时,说明以满足要求,可以跳出递归
        if ( path.size() == k) {
            result.add(new ArrayList<>(path));
            return;
        }
        //剪枝的目的是当for循环起始位置之后的元素个数已经不足我们需要的元素个数时,那么就停止搜索
        //已经选择的元素个数:path.size();
        //还需要的元素个数为: k - path.size()
        //剪枝优化 i的取值范围[startIndex, n - (k - path.size()) + 1]
        for( int i = startIndex; i <= n - (k - path.size()) + 1; i++) {
            path.add(i);//处理节点
            combineHelper(n, k, i + 1);//递归
            path.removeLast();//回溯,撤销处理的节点
        }
    }
}