【递归 &回溯】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 中的所有元素 互不相同
算法分析

解题思路

二进制

由于每个数有选和不选两种情况,因此总共有 2^n 种情况,用二进制 02^n 表示所有的情况,在某种情况i中,若该二进制i的第j位是1,则表示第j位这个数选,加入到path中,枚举完i这种情况,将path加入到ans链表中

class Solution {
    static List<List<Integer>> ans = new ArrayList<List<Integer>>();
    static List<Integer> path = new ArrayList<Integer>();
    public List<List<Integer>> subsets(int[] nums) {
        ans.clear();
        int n = nums.length;
        for(int i = 0;i < 1 << n;i ++)
        {
            path.clear();
            for(int j = 0;j < n;j ++)
            {
                if((i >> j & 1) == 1)
                    path.add(nums[j]);
            }
            ans.add(new ArrayList<Integer>(path));
        }
        return ans;
    }
}

复杂性分析

时间复杂度:O(2^n)

空间复杂度:O(n)

相关推荐
CV工程师小林6 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
天玑y6 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
sjsjs117 小时前
【数据结构-一维差分】力扣1893. 检查是否区域内所有整数都被覆盖
数据结构·算法·leetcode
m0_571957587 小时前
Java | Leetcode Java题解之第406题根据身高重建队列
java·leetcode·题解
山脚ice7 小时前
【Hot100】LeetCode—72. 编辑距离
算法·leetcode
鱼跃鹰飞8 小时前
Leetcode面试经典150题-349.两个数组的交集
算法·leetcode·面试
大二转专业9 小时前
408算法题leetcode--第七天
考研·算法·leetcode
戊子仲秋12 小时前
【LeetCode】每日一题 2024_9_19 最长的字母序连续子字符串的长度(字符串,双指针)
算法·leetcode·职场和发展
程序猿练习生15 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
MogulNemenis17 小时前
力扣150题——位运算
数据结构·算法·leetcode