4. 子集

题目描述

给你一个整数数组nums,数组中的元素互不相同。返回该数组所有可能的子集(幂集)。
解集不能包含重复的子集。你可以按任意顺序返回解集。

题目链接

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

说明

复杂度分析

时间复杂度分析:
O(n * 1 << n)
一共1 << n个状态,每种状态需要O(n)的时间来构造子集。
空间复杂度分析:
O(n)
即构造子集使用的临时数组t的空间代价。

代码

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 i = 0; i < (1 << n); i++) {
            t.clear();
            for (int j = 0; j < n; j++) {
                if ((i & 1 << j) != 0) {
                    t.add(nums[j]);
                }
            }
            ans.add(new ArrayList<Integer>(t));
        }
        return ans;
    }
}
posted @ 2022-01-25 10:49  jsqup  阅读(21)  评论(0编辑  收藏  举报