[Leetcode]Subsets

135人阅读 评论(0)

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

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

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：31264次
• 积分：1076
• 等级：
• 排名：千里之外
• 原创：78篇
• 转载：10篇
• 译文：1篇
• 评论：7条
文章分类
阅读排行
评论排行
最新评论