代码随想录算法训练营第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);
        }
    }
}
相关推荐
超的小宝贝4 分钟前
数据结构算法(C语言)
c语言·数据结构·算法
木子.李3476 小时前
排序算法总结(C++)
c++·算法·排序算法
闪电麦坤957 小时前
数据结构:递归的种类(Types of Recursion)
数据结构·算法
Gyoku Mint8 小时前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
纪元A梦8 小时前
分布式拜占庭容错算法——PBFT算法深度解析
java·分布式·算法
px不是xp8 小时前
山东大学算法设计与分析复习笔记
笔记·算法·贪心算法·动态规划·图搜索算法
枫景Maple9 小时前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode
鑫鑫向栄9 小时前
[蓝桥杯]修改数组
数据结构·c++·算法·蓝桥杯·动态规划
鑫鑫向栄9 小时前
[蓝桥杯]带分数
数据结构·c++·算法·职场和发展·蓝桥杯