leetcode_78子集

1. 题意

给定一个不含有重复数字的数列,求所有的子集。

2. 题解

子集型回溯,可以直接用dfs进行搜索;也可以用二进制来进行枚举。

2.1 选或不选
c 复制代码
class Solution {
public:
    void dfs(vector<vector<int>> &ans,vector<int> &tmp,
             vector<int> &nums, int depth) {
        if (depth == nums.size()) {
            ans.emplace_back(tmp );
            return;
        }

            dfs(ans, tmp, nums, depth + 1);
            tmp.push_back(nums[depth]);
            dfs(ans, tmp, nums, depth + 1);
            tmp.pop_back();
    }


    vector<vector<int>> subsets(vector<int>& nums) {
        
        vector<vector<int>> ans;
        vector<int> tmp;
        dfs( ans, tmp, nums, 0);
        return ans;
    }
};
2.2 选哪个
cpp 复制代码
class Solution {
public:
    void dfs(vector<vector<int>> &ans,vector<int> &tmp,
             vector<int> &nums, int depth) {
        
        ans.emplace_back(tmp);
        for (int i = depth;i < nums.size(); i++) {
            tmp.push_back(nums[i]);
            dfs(ans, tmp, nums, i + 1);
            tmp.pop_back();
        }
    }


    vector<vector<int>> subsets(vector<int>& nums) {
        
        vector<vector<int>> ans;
        vector<int> tmp;
        dfs( ans, tmp, nums, 0);
        return ans;
    }
};
2.3 二进制枚举
cpp 复制代码
class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        
        vector<vector<int>> ans;
        int sz = nums.size();

        for (int i = 0;i < (1 << sz); i++) {
            vector<int> tmp;
            for (int j = 0;j < sz;j++) {
                if (i & (1 << j))
                    tmp.push_back(nums[j]);
            }
            ans.emplace_back( tmp );
        }

        return ans;
    }
};

参考

0x3f题解

相关推荐
天选之女wow3 分钟前
【代码随想录算法训练营——Day59】图论——47.参加科学大会、94.城市间货物运输I
算法·图论
CoovallyAIHub12 分钟前
1.2MB超轻量模型实现草莓苗精准分级检测与定位,准确率超96%
深度学习·算法·计算机视觉
CoovallyAIHub30 分钟前
终结AI偏见!Sony AI发布Nature论文与FHIBE数据集,重塑公平性评估基准
深度学习·算法·计算机视觉
7澄133 分钟前
深入解析 LeetCode 1572:矩阵对角线元素的和 —— 从问题本质到高效实现
java·算法·leetcode·矩阵·intellij-idea
ALex_zry35 分钟前
c20 字符串处理优化可选方案
算法
阳光明媚sunny38 分钟前
分糖果算法题
java·算法
卡提西亚41 分钟前
一本通网站1125题:矩阵乘法
c++·算法·矩阵·编程题·一本通
程序员东岸42 分钟前
数据结构精讲:从栈的定义到链式实现,再到LeetCode实战
c语言·数据结构·leetcode
laocooon5238578861 小时前
大数的阶乘 C语言
java·数据结构·算法
Boop_wu2 小时前
[Java EE] 多线程 -- 初阶(1)
java·jvm·算法