代码随想录算法训练营第24天|回溯理论基础、77.组合

目录

一、回溯理论基础


二、力扣77.组合问题

2.1 题目

2.2 思路

回溯三部曲:递归函数参数及返回值;确定终止条件;单层递归逻辑。

剪枝:

有些不符合条件的就不必去遍历了,即path.size() + 剩余的数的个数已经不满足k的大小了;

修改for循环的终止条件:找到刚好符合k的边界值,即n-(k-path.size())+1.

2.3 代码

第一次出错的代码:

cpp 复制代码
class Solution {
    public List<List<Integer>> res = new ArrayList<>();
    public List<Integer> path = new ArrayList<>();

    public List<List<Integer>> combine(int n, int k) {
        //回溯的组合问题
        backTracking(n,k,1);
        return res;
    }
    public void backTracking(int n,int k,int startIndex){
        //递归终止条件
        if(path.size() == k){
            res.add(path);
            return;
        }

        //单层递归逻辑
        for(int i = startIndex;i<=n;i++){
            path.add(i);
            backTracking(n,k,i+1);
            //回溯
            path.remove(path.size()-1);
        }
    }
}

修改后的代码:

(注意这里不能直接add path集合,否则都加入的是同一个集合,最后结果集都是同一个path的最终状态)

cpp 复制代码
class Solution {
    public List<List<Integer>> res = new ArrayList<>();
    public List<Integer> path = new ArrayList<>();

    public List<List<Integer>> combine(int n, int k) {
        //回溯的组合问题
        backTracking(n,k,1);
        return res;
    }
    public void backTracking(int n,int k,int startIndex){
        //递归终止条件
        if(path.size() == k){
            res.add(new ArrayList<>(path));//注意这里不能直接add path集合,否则都加入的是同一个集合,最后结果集都是同一个path的最终状态
            return;
        }

        //单层递归逻辑
        for(int i = startIndex;i<=n;i++){
            path.add(i);
            backTracking(n,k,i+1);
            //回溯
            path.remove(path.size()-1);
        }
    }
}

剪枝后的代码:

cpp 复制代码
class Solution {
    public List<List<Integer>> res = new ArrayList<>();
    public List<Integer> path = new ArrayList<>();

    public List<List<Integer>> combine(int n, int k) {
        //回溯的组合问题
        backTracking(n,k,1);
        return res;
    }
    public void backTracking(int n,int k,int startIndex){
        //递归终止条件
        if(path.size() == k){
            res.add(new ArrayList<>(path));//注意这里不能直接add path集合,否则都加入的是同一个集合,最后结果集都是同一个path的最终状态
            return;
        }

        //单层递归逻辑
        //剪枝优化
        for(int i = startIndex;i<= n-(k-path.size())+1;i++){
            path.add(i);
            backTracking(n,k,i+1);
            //回溯
            path.remove(path.size()-1);
        }
    }
}
相关推荐
山登绝顶我为峰 3(^v^)323 分钟前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Two_brushes.1 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
森焱森3 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
QuantumStack5 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
写个博客6 小时前
暑假算法日记第一天
算法
绿皮的猪猪侠6 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
hie988947 小时前
MATLAB锂离子电池伪二维(P2D)模型实现
人工智能·算法·matlab
杰克尼7 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
.30-06Springfield8 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习
我不是哆啦A梦8 小时前
破解风电运维“百模大战”困局,机械版ChatGPT诞生?
运维·人工智能·python·算法·chatgpt