题解 | #集合的所有子集(一)#

集合的所有子集(一)

http://www.nowcoder.com/practice/c333d551eb6243e0b4d92e37a06fbfc9

1. 递归

每次递归,当前位置的数字可以选择或者不选择。

class Solution {
public:
    vector<vector<int> > res;
    void dfs(vector<int>& S, vector<int> tmp, int start){
        res.push_back(tmp);
        if(start == S.size()){
            return;
        }
        for(size_t i = start; i < S.size(); i++){
            tmp.push_back(S[i]);
            dfs(S, tmp, i + 1);
            tmp.pop_back();
        }
    }
    
    vector<vector<int> > subsets(vector<int> &S) {
        if(S.empty()) return res;
        sort(S.begin(), S.end());
        dfs(S, vector<int>(), 0);
        return res;
    }
};

2. 位运算:n个元素的子集共有2^n个.

将0~2^n-1的每一个数转换为n位的二进制数来看,如果第0~n-1的某一位为1,则选择对应位置的数。遍历完即可获得所有子集。

class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        vector<vector<int> > res;
        vector<int> tmp;
        int n = S.size();
        if(S.empty()) return res;
        sort(S.begin(), S.end());
        for(int i = 0; i < pow(2, n); i++){
            for(int j = 0; j < n; j++){
                if((i >> j) & 1){
                    tmp.push_back(S[j]);
                }
            }
            res.push_back(tmp);
            tmp.clear();
        }
        return res;
    }
};
全部评论

相关推荐

09-16 14:33
已编辑
南京大学 Java
最近福耀科技大学好火啊,号称保底25w年薪就业,有不少高分学生都报了,兄弟们你有这个分,报传统92还是它?
ITTM:如果真的像宣传所说的能给到25w保底薪资,985也没啥吸引力了,这年头,读书不就是为了能多赚点钱嘛
点赞 评论 收藏
分享
09-21 21:14
门头沟学院
点赞 评论 收藏
分享
我不行了,我真过不了第二关
码农索隆:嘿,哥们连界面都进去去,更别提玩了
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务