78. Subsets

来源:互联网 发布:程序员开发手册 编辑:程序博客网 时间:2024/06/10 19:39

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[  [3],  [1],  [2],  [1,2,3],  [1,3],  [2,3],  [1,2],  []]

思路:用格雷码对应子集
000 001 010 011 101 110 111
[] [1] [2] [1,2] [1,3] [2,3] [1,2,3]

class Solution {public:    vector<string> BRGC(int n){        if(n == 0) return {"0"};        if(n == 1) return {"0", "1"};        else {            vector<string> L1 = BRGC(n - 1);            vector<string> L2(L1);            vector<string> L;            reverse(L2.begin(), L2.end());            for(int i = 0; i < L1.size(); ++i)                L1[i].insert(L1[i].begin(), '0');            for(int i = 0; i < L2.size(); ++i)                L2[i].insert(L2[i].begin(), '1');            L1.insert(L1.end(), L2.begin(), L2.end());            L.insert(L.end(), L1.begin(), L1.end());            return L;        }    }    vector<vector<int>> subsets(vector<int>& nums) {        int n = nums.size();        vector<string> L = BRGC(n);        vector<vector<int>> ans;        for(int i = 0; i < L.size(); ++i){            vector<int> v;            for(int j = 0; j < n; ++j){                if(L[i][j] == '1'){                    v.push_back(nums[j]);                }            }            ans.push_back(v);        }        return ans;    }};
0 0
原创粉丝点击