代码随想录算法训练营第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);
        }
    }
}
相关推荐
凌肖战2 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
weixin_478689762 小时前
十大排序算法汇总
java·算法·排序算法
luofeiju3 小时前
使用LU分解求解线性方程组
线性代数·算法
SKYDROID云卓小助手3 小时前
无人设备遥控器之自动调整编码技术篇
人工智能·嵌入式硬件·算法·自动化·信号处理
ysa0510303 小时前
数论基础知识和模板
数据结构·c++·笔记·算法
GEEK零零七3 小时前
Leetcode 1103. 分糖果 II
数学·算法·leetcode·等差数列
今天背单词了吗9804 小时前
算法学习笔记:7.Dijkstra 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·开发语言·数据结构·笔记·算法
重庆小透明5 小时前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq5 小时前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
clock的时钟6 小时前
暑期数据结构第一天
数据结构·算法