【递归 &回溯】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 种情况,用二进制 0 到 2^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)

相关推荐
Nazarick6 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴6 小时前
斐波那契数列题解
算法·leetcode
Tisfy9 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
Navigator_Z13 小时前
LeetCode //C - 1332. Remove Palindromic Subsequences
c语言·算法·leetcode
Nazarick14 小时前
力扣LeetCode热题(3)
java·算法·leetcode·贪心算法
Rain的Java大神之路14 小时前
LeetCode 46 全排列:从「及格答案」到让面试官眼前一亮的三种写法
后端·leetcode·面试
Shaoshing16 小时前
LeetCode100 152.乘积最大子数组
数据结构·算法·leetcode
吞下星星的少年·-·16 小时前
力扣 162. 寻找峰值(枚举,二分查找)
算法·leetcode·枚举·二分
Shaoshing1 天前
LeetCode 921.使括号括号有效的最少添加
java·算法·leetcode·职场和发展
圣保罗的大教堂1 天前
leetcode 3884. 双端字符匹配 简单
leetcode