代码随想录算法训练营第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);
        }
    }
}
相关推荐
Funny_AI_LAB16 分钟前
MetaAI最新开源Llama3.2亮点及使用指南
算法·计算机视觉·语言模型·llama·facebook
NuyoahC23 分钟前
算法笔记(十一)——优先级队列(堆)
c++·笔记·算法·优先级队列
jk_10126 分钟前
MATLAB中decomposition函数用法
开发语言·算法·matlab
penguin_bark1 小时前
69. x 的平方根
算法
这可就有点麻烦了1 小时前
强化学习笔记之【TD3算法】
linux·笔记·算法·机器学习
苏宸啊1 小时前
顺序表及其代码实现
数据结构·算法
lin zaixi()2 小时前
贪心思想之——最大子段和问题
数据结构·算法
FindYou.2 小时前
C - Separated Lunch
算法·深度优先
夜雨翦春韭2 小时前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
Kent_J_Truman2 小时前
【平方差 / C】
算法