【递归 &回溯】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)

相关推荐
LYFlied38 分钟前
【每日算法】LeetCode 64. 最小路径和(多维动态规划)
数据结构·算法·leetcode·动态规划
sin_hielo2 小时前
leetcode 3074
数据结构·算法·leetcode
程序员-King.2 小时前
day124—二分查找—最小化数组中的最大值(LeetCode-2439)
算法·leetcode·二分查找
im_AMBER4 小时前
Leetcode 85 【滑动窗口(不定长)】最多 K 个重复元素的最长子数组
c++·笔记·学习·算法·leetcode·哈希算法
2401_841495645 小时前
【LeetCode刷题】跳跃游戏Ⅱ
数据结构·python·算法·leetcode·数组·贪心策略·跳跃游戏
rannn_1116 小时前
【SQL题解】力扣高频 SQL 50题|DAY5
数据库·后端·sql·leetcode·题解
LYFlied6 小时前
【每日算法】LeetCode 279. 完全平方数(动态规划)
前端·算法·leetcode·面试·动态规划
努力学算法的蒟蒻7 小时前
day43(12.24)——leetcode面试经典150
算法·leetcode·面试
元亓亓亓7 小时前
LeetCode--279. 完全平方数--中等
算法·leetcode·动态规划
历程里程碑8 小时前
LeetCode128:哈希集合巧解最长连续序列
开发语言·数据结构·c++·算法·leetcode·哈希算法·散列表