[Leetcode]Subsets

Subsets My Submissions Question
Total Accepted: 72388 Total Submissions: 247343 Difficulty: Medium
Given a set of distinct integers, nums, return all possible subsets.

Note:
Elements in a subset must be in non-descending order.
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],
[]
]
Subscribe to see which companies asked this question
我是按照我博客里那种方法做的,有些地方不太一样,用adapter模式(允许我装个逼)搞一下,结果对顺序还有要求。。。干脆每次插入都排个序,这样时间就上去了,12ms。如果不排序就要修改一下getSubstring()这个就行,可是我懒得修改了。当然用DFS做也没问题,就比较简单了。下面把两种方法都贴出来

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        int len = nums.size();
        string str;
        for(int i = 0;i != len;++i){
            str.push_back(nums[i] + '0');
        }

        vector<string> res = func(str);

        vector<vector<int> >    ans;
        ans.push_back({});
        for(int i = 0;i != res.size();++i){
            vector<int> tem;
            for(int j = 0;j != res[i].size();++j){
                tem.push_back(res[i][j] - '0');
            }
            sort(tem.begin(),tem.end());
            ans.push_back(tem);
        }
        sort(ans.begin(),ans.end());
        return ans;
    }

vector<string> func(string str){
    int len = str.size();
    vector<string>  res;
    int num = 1 << len;
    num = num - 1;
    //cout << num << endl;
    for(int i = 1;i <= num;++i){
        string tem = getSubstring(str,i);
        res.push_back(tem);
    }
    return res;
}
string getSubstring(string str,int num){
    string tem;
    //cout << num << endl;
    int len = str.size();
    int n = len - 1;
    while(num){
        if(num & 0x1){
            tem += str[n];
        }
        num = num >> 1;
        --n;
    }
    return tem;
}
};

DFS:

class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    vector<vector<int>> res;
    vector<int> path;
    dfs(nums, 0, path, res);
    return res;
}

void dfs(vector<int>& nums, int index, vector<int>& path, vector<vector<int>>& res) {
    res.push_back(path);
    for (unsigned int i = index; i < nums.size(); i++) {
        path.push_back(nums[i]);
        dfs(nums, i+1, path, res);
        path.pop_back();
    }
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值