LeetCode78. 子集(2024秋季每日一题 58)

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

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

示例 1:

输入:nums = [1,2,3]

输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

示例 2:

输入:nums = [0]

输出:[[],[0]]

提示:

1 < = n u m s . l e n g t h < = 10 1 <= nums.length <= 10 1<=nums.length<=10
− 10 < = n u m s [ i ] < = 10 -10 <= nums[i] <= 10 −10<=nums[i]<=10
nums 中的所有元素 互不相同


思路:

  • 用二进制枚举每一位 选/或者不选(对应原数组的下标)
  • 将二进制中为 1 的位置对应的元素放入到子集数组中
  • 将所有的子集数组加入最终的答案数组返回即可
cpp 复制代码
class Solution {
public:
    vector<vector<int>> res;
    set<vector<int>> ans;
    vector<vector<int>> subsets(vector<int>& nums) {
        int n = nums.size();
        for(int i = 0; i < (1 << n); i++){
            vector<int> v;
            for(int j = 0; j < n; j++)
                if(i >> j & 1)
                    v.push_back(nums[j]);
            res.push_back(v);
        }
        return res;   
    }
};
相关推荐
汉克老师1 天前
GESP2025年12月认证C++七级真题与解析(单选题8-15)
c++·dfs·bfs·二分·强联通分量·gesp7级·gesp七级
kylezhao20194 天前
C# 数组核心全面详解
c#·数组
2401_841495645 天前
【LeetCode刷题】寻找重复数
数据结构·python·算法·leetcode·链表·数组·重复数
2401_8414956411 天前
【LeetCode刷题】零钱兑换
数据结构·python·算法·leetcode·动态规划·数组·时间复杂度
l1t11 天前
postgresql递归查询指定搜索顺序的方法
数据库·postgresql·dfs·递归·cte
2401_8414956411 天前
【LeetCode刷题】打家劫舍
数据结构·python·算法·leetcode·动态规划·数组·传统dp数组
l1t12 天前
sqlite递归查询指定搜索顺序的方法
数据库·sql·sqlite·dfs·递归·cte
Irene199112 天前
JavaScript 字符串和数组方法总结(默写版:同9则6 Str21 Arr27)
javascript·字符串·数组·方法总结
l1t12 天前
在postgres和duckdb中比较两个数组并只挑选不匹配的元素
数据库·sql·postgresql·数组·duckdb