回溯算法之-子集

关于回溯法的模版请看: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);
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • LeetCode 78.子集 问题描述 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)...
    花枝俏土豆阅读 1,099评论 0 0
  • 《算法练习-文章汇总》[https://www.jianshu.com/p/fc7c0e8cc5cb] 分治:是递...
    一亩三分甜阅读 2,880评论 0 0
  • 题目描述:给定一组不含重复元素的整数数组nums,返回该数组所有可能的子集(幂集)。 说明:解集不能包含重复的子集...
    windUtterance阅读 1,463评论 0 0
  • 此为回溯算法刷题的一些代码,希望能给读者以启发; 刷题目录: 46. 全排列 47. 全排列 II 78. 子集 ...
    uestcxbc阅读 2,726评论 0 0
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    余生动听阅读 13,597评论 0 11

友情链接更多精彩内容