0
点赞
收藏
分享

微信扫一扫

Day42 子集

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

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

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

示例1:

示例2:

提示:

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. 迭代法实现子集枚举

    • 时间复杂度:O(n×2^n)
    • 空间复杂度:O(n)
  2. 递归法实现子集枚举

    • 时间复杂度:O(n×2^n)
    • 空间复杂度:O(n)
举报

相关推荐

0 条评论