Day42 子集

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

https://leetcode-cn.com/problems/subsets/

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

示例1:

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

示例2:

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

提示:

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

Java解法

思路:

  • 所有子集,类似一个排列组合的问题,尝试循环处理,但是漏掉了两两配合
  • 参考官方解使用回溯处理
  • 每个位置只有添加不添加两种状态,因此添加,复位不添加处理
package sj.shimmer.algorithm.m2;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SJ on 2021/3/7.
 */

class D42 {
    public static void main(String[] args) {
        System.out.println(subsets(new int[]{1, 2, 3}));
    }
    static List<Integer> t = new ArrayList<Integer>();
    static List<List<Integer>> result = new ArrayList<List<Integer>>();

    public static List<List<Integer>> subsets(int[] nums) {
        backTract(0, nums);
        return result;
    }


    public static void  backTract(int index,int[] nums) {
        if (index == nums.length) {
            result.add(new ArrayList<Integer>(t));
            return;
        }
        t.add(nums[index]);
        backTract(index + 1, nums);
        t.remove(t.size() - 1);
        backTract(index + 1, nums);
    }
}

官方解

https://leetcode-cn.com/problems/subsets/solution/zi-ji-by-leetcode-solution/

  1. 迭代法实现子集枚举

    通过存在不存在转换为 二进制来表示对应集合的二机制数

    class Solution {
        List<Integer> t = new ArrayList<Integer>();
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
    
        public List<List<Integer>> subsets(int[] nums) {
            int n = nums.length;
            for (int mask = 0; mask < (1 << n); ++mask) {
                t.clear();
                for (int i = 0; i < n; ++i) {
                    if ((mask & (1 << i)) != 0) {
                        t.add(nums[i]);
                    }
                }
                ans.add(new ArrayList<Integer>(t));
            }
            return ans;
        }
    }
    
    • 时间复杂度:O(n×2^n)
    • 空间复杂度:O(n)
  2. 递归法实现子集枚举

    参考处理

    • 时间复杂度:O(n×2^n)
    • 空间复杂度:O(n)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值