代码随想录算法训练营第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);
        }
    }
}
相关推荐
石去皿32 分钟前
力扣hot100 91-100记录
算法·leetcode·职场和发展
SsummerC2 小时前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
2301_807611493 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯
SsummerC4 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划
好易学·数据结构5 小时前
可视化图解算法:二叉树的最大深度(高度)
数据结构·算法·二叉树·最大高度·最大深度·二叉树高度·二叉树深度
程序员-King.5 小时前
day47—双指针-平方数之和(LeetCode-633)
算法·leetcode
阳洞洞5 小时前
leetcode 1035. Uncrossed Lines
算法·leetcode·动态规划·子序列问题
小鹿鹿啊6 小时前
C语言编程--15.四数之和
c语言·数据结构·算法
rigidwill6666 小时前
LeetCode hot 100—最长有效括号
数据结构·c++·算法·leetcode·职场和发展