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题解

相关推荐
笨笨阿库娅8 小时前
从零开始的算法基础学习
学习·算法
不想睡觉_8 小时前
优先队列priority_queue
c++·算法
那个村的李富贵16 小时前
CANN加速下的AIGC“即时翻译”:AI语音克隆与实时变声实战
人工智能·算法·aigc·cann
power 雀儿16 小时前
Scaled Dot-Product Attention 分数计算 C++
算法
琹箐17 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
renhongxia117 小时前
如何基于知识图谱进行故障原因、事故原因推理,需要用到哪些算法
人工智能·深度学习·算法·机器学习·自然语言处理·transformer·知识图谱
坚持就完事了17 小时前
数据结构之树(Java实现)
java·算法
算法备案代理17 小时前
大模型备案与算法备案,企业该如何选择?
人工智能·算法·大模型·算法备案
赛姐在努力.18 小时前
【拓扑排序】-- 算法原理讲解,及实现拓扑排序,附赠热门例题
java·算法·图论
野犬寒鸦19 小时前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法