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

相关推荐
和光同尘@41 分钟前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
CHEN5_0241 分钟前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode
songx_991 小时前
leetcode18(无重复字符的最长子串)
java·算法·leetcode
max5006001 小时前
实时多模态电力交易决策系统:设计与实现
图像处理·人工智能·深度学习·算法·音视频
其古寺2 小时前
贪心算法与动态规划:数学原理、实现与优化
算法·贪心算法·动态规划
rit84324992 小时前
基于灰狼算法(GWO)优化支持向量回归机(SVR)参数C和γ的实现
c语言·算法·回归
蒋士峰DBA修行之路2 小时前
实验五 静态剪枝
数据库·算法·剪枝
蒋士峰DBA修行之路2 小时前
实验六 动态剪枝
数据库·算法·剪枝
Tim_103 小时前
【算法专题训练】20、LRU 缓存
c++·算法·缓存
Lris-KK3 小时前
【Leetcode】高频SQL基础题--1341.电影评分
sql·leetcode