回溯

作者: 你大爷终归是你大爷 | 来源:发表于2022-06-05 11:47 被阅读0次

回朔算法是使用递归的方式,遍历所有的状态,一般借助数组等结构进行“剪枝”,较少遍历的次数。

解决的是 子集、组合、排列 问题。注意边界条件。
子集和排列和顺序无关,要借助位置信息防止重复;
排列和位置无关,只需判断辅助数据结构(path)中是否包含当前元素

下文介绍这几种的标准代码。

1、子集

力扣78题:给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

class Solution {

    List<List<Integer>> res = new ArrayList();
    List<Integer> path = new ArrayList();

    public List<List<Integer>> subsets(int[] nums) {
        dfs(nums, 0);
        return res;
    }

    // 注意index的用法
    public void dfs(int[] nums, int index) {
        res.add(new ArrayList(path));
        for(int i=index;i<nums.length;i++) {
            path.add(nums[i]);
            dfs(nums, i+1);
            path.remove(path.size()-1);
        }
    }
}

2、组合

组合是在子集的基础上进行剪枝,过程中不匹配直接返回,不在继续递归。
力扣77:给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。

class Solution {

    List<List<Integer>> res = new ArrayList();
    List<Integer> path = new ArrayList();

    public List<List<Integer>> combine(int n, int k) {
        dfs(n, k, 1);
        return res;
    }

    public void dfs(int n, int k, int index) {
        // 剪枝:组合是特定的子集,保留符合的
        if(k == path.size()) {
            res.add(new ArrayList(path));
            return ;
        }
        for(int i=index;i<=n;i++) {
            path.add(i);
            dfs(n, k, i+1);
            path.remove(path.size()-1);
        }
    }
}

3、排列

力扣46题: 全排列 给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

class Solution {

    List<List<Integer>> res = new ArrayList();
    List<Integer> path = new ArrayList();

    public List<List<Integer>> permute(int[] nums) {
        dfs(nums);
        return res;
    }

    public void dfs(int[] nums) {
        if(path.size() == nums.length) {
            res.add(new ArrayList(path));
            return;
        }
        for(int i=0;i<nums.length;i++) {
            if(path.contains(nums[i])) {
                continue;
            }
            path.add(nums[i]);
            dfs(nums);
            path.remove(path.size()-1);
        }

    }
}

相关文章

  • 回溯算法

    回溯算法 回溯算法介绍   回溯算法并不是非常复杂的算法, 很多人接触过但是未必知道这是回溯算法; 典型的回溯算法...

  • 回溯算法:八皇后问题和0-1背包问题

    文章结构 如何理解回溯算法 回溯算法的经典应用 完整源码 图片来源 1. 如何理解回溯算法 1.1 什么是回溯算法...

  • LeetCode之回溯算法

    回溯法也可以叫做回溯搜索法,它是一种搜索的方式。回溯是递归的副产品,只要有递归就会有回溯。因为回溯的本质是穷举,穷...

  • N皇后

    回溯法核心代码: n皇后问题回溯法

  • Algorithm进阶计划 -- 回溯算法

    滑动窗口算法回溯算法框架回溯算法运用 1. 回溯算法框架 回溯算法,是类似枚举的搜索尝试过程,主要是在搜索尝试过程...

  • 算法思想 - 回溯算法

    回溯思想 回溯算法的思想非常好理解,之前我们也使用回溯的思想完成了图的深度优先搜索。简单来说,回溯的思想是这样的:...

  • 回溯

    为什么要把文章取这个名字呢?因为前两天去参加了考试,这是我的作文题目,努力了一小段青春的记忆,在回溯中也许金榜...

  • 回溯

    前几天拿到课程表,仔细看了一下,钟杰老师两天的课,一天女孩,一天男孩,我心想,这是讲的大孩子的课,跟我们幼儿园...

  • 回溯

    请假了三天的我,看到昨天的微信消息时,着实是有些慌张的。前天晚上加班到凌晨一点钟的工作几乎白费,全部要重新开...

  • 回溯

    诗人说一片叶写满了天空的心事 当你拿起呼吸 会记起蓝色的记忆 可我不愿离那里太近 就像夏日我不去找寻树荫 歌手说破...

网友评论

      本文标题:回溯

      本文链接:https://www.haomeiwen.com/subject/xvqzprtx.html