leecode 77 组合 回溯法和剪枝

该代码实现了一个用于组合问题的Java类Solution,使用递归方法backTracking进行组合计算。方法接受整数n和k,生成所有可能的k个数的组合,结果存储在List<List<Integer>>中。关键在于递归过程中更新路径(path)并剪枝,避免重复计算。
摘要由CSDN通过智能技术生成
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    int selectNum;
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> combine(int n, int k) {
        this.selectNum = k;
        backTracking(0, 1, n);
        return res;
    }

    public void backTracking(int nowNum, int startIndex, int endIndex) {
        if (selectNum == nowNum) {
            // 需要传递一个新的对象,不然存储的指向是同一个path
            res.add(new ArrayList<>(path));
            return;
        }
        // 剪纸的i是每层循环可以取到的最后一个选项 ,以 4 4为例子,1就是最后一个可以选的
        for (int i = startIndex; i <= endIndex - (selectNum - path.size()) + 1; i++){
            // 添加的当前选择可以移动的元素也就是i
            path.add(i);
            // startIndex的参数应该是i + 1,表示取集合中的下一个位置
            backTracking(nowNum + 1, i + 1, endIndex);
            path.removeLast();
        }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值