美文网首页
回溯算法之-子集

回溯算法之-子集

作者: 不知名的程序员 | 来源:发表于2021-03-14 18:45 被阅读0次

关于回溯法的模版请看:https://www.jianshu.com/p/2a9856b96a86

leetcode 78 子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。解集 不能 包含重复的子集。你可以按 任意顺序 返回解集
这个题和组合总和的题类似,只不过我们将解集收集的地方不同,套回溯法模版

public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        subsetsHelp(res, new ArrayList<>(), nums, 0);
        return res;
    }

    private void subsetsHelp(List<List<Integer>> res, ArrayList<Integer> list, int[] nums, int index) {
      // 在递归开始的地方将路径进行收集,一边回溯一边收集
        res.add(new ArrayList<>(list));
        for (int i = index; i < nums.length; i++) {
            list.add(nums[I]);
            subsetsHelp(res, list, nums, i + 1);
            list.remove(list.size()-1);
        }   
    }

Leetcode 90 子集2

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
该题的解法和组合总和2基本相同

public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        subsetsWithDupHelp(res, new ArrayList<>(), nums, 0);
        return res;
    }

    private void subsetsWithDupHelp(List<List<Integer>> res, ArrayList<Integer> list, int[] nums, int index) {
        res.add(new ArrayList<>(list));
        for (int i = index; i < nums.length; i++) {
            // 同一层若相同元素被使用过则跳过
            if (i > index && nums[i] == nums[i-1]) {
                continue;
            }
            list.add(nums[I]);
            subsetsWithDupHelp(res, list, nums, i+1);
            list.remove(list.size()-1);
        }
    }

相关文章

  • 回溯算法之-子集

    关于回溯法的模版请看:https://www.jianshu.com/p/2a9856b96a86[https:/...

  • 回溯算法

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

  • [回溯算法]python解决N皇后问题(20行代码)

    如果读者对于回溯算法思路解法还不是很了解,可以先点击链接查阅我之前的一篇博文《算法之【回溯算法】详解[https:...

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

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

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

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

  • 回溯递归算法

    回溯大法严重依赖【递归】 1、求子集 78. 子集[https://leetcode-cn.com/problem...

  • LeetCode 0078. Subsets子集【Python】

    LeetCode 0078. Subsets子集【Medium】【Python】【回溯】 Problem Leet...

  • 回溯算法总结

    回溯法学习总结 回溯算法也是算法导论中常用的算法,回溯算法类似于暴力求解算法,经常用在求可能解的问题。下面我将从三...

  • 算法之回溯算法详解

    回溯算法 定义 回溯算法实际上基于DFS(深度优先搜索)的一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问...

  • 回溯算法团灭子集、排列、组合问题

    读完本文,你可以去力扣拿下如下题目: 78.子集[https://leetcode-cn.com/problems...

网友评论

      本文标题:回溯算法之-子集

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