• Medium | LeetCode 78. 子集 | 回溯


    78. 子集

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

    解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

    示例 1:

    输入:nums = [1,2,3]
    输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
    

    示例 2:

    输入:nums = [0]
    输出:[[],[0]]
    

    提示:

    • 1 <= nums.length <= 10
    • -10 <= nums[i] <= 10
    • nums 中的所有元素 互不相同

    解题思路

    方法一: 回溯法

    class Solution {
        private List<List<Integer>> res;
     
        public List<List<Integer>> subsets(int[] nums) {
            res = new ArrayList<List<Integer>>();
            getSubSets(nums, 0, new LinkedList<>());
            return res;
        }
    
        public void getSubSets(int[] nums, int index, LinkedList<Integer> curSet) {
            // 递归出口
            if (index == nums.length) {
                res.add(new ArrayList<>(curSet));
                return;
            }
            // 先把当前元素加进集合
            curSet.addLast(nums[index]);
            // 递归后面的部分
            getSubSets(nums, index + 1, curSet);
            // 然后移除当前元素
            curSet.removeLast();
            // 递归后面的部分
            getSubSets(nums, index + 1, curSet);
        }
    }
    

    方法二:枚举

    每个数字添加或者不添加, 有2^N 中情况。可以使用从0到2^N的数字的二进制为掩码, 来标记, 每个数字是否出现。

    public List<List<Integer>> subsets(int[] nums) {
        int n = nums.length;
        List<Integer> t = new ArrayList<Integer>();
    	List<List<Integer>> ans = new ArrayList<List<Integer>>();
        // 第一个For循环, 枚举2^N中情况
        for (int mask = 0; mask < (1 << n); ++mask) {
            t.clear();
            // 第二个For循环, 遍历掩码的每一位, 选取相应的数字
            for (int i = 0; i < n; ++i) {
                if ((mask & (1 << i)) != 0) {
                    t.add(nums[i]);
                }
            }
            // 将每一个掩码对应的一组数字加进结果集
            ans.add(new ArrayList<Integer>(t));
        }
        return ans;
    }
    
  • 相关阅读:
    SM9-加解密
    SM9-密钥封装
    Cookie和Session的区别
    直观简单讲解单点登录的流程原理
    分布式环境下Session共享问题解决和原理讲解
    以微博开发平台为例,使用社交账号登录网站
    MD5&MD5盐值加密到BCryptPasswordEncoder
    CompletableFuture异步线程
    git clone 出现fatal: unable to access 'https://github 类错误解决方法
    Python包及其定义和引用详解
  • 原文地址:https://www.cnblogs.com/chenrj97/p/14359843.html
Copyright © 2020-2023  润新知