描述
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order. e solution set must not contain duplicate
subsets. For example, If S = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order. e solution set must not contain duplicate
subsets. For example, If S = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool comp(const vector<int> &a, const vector<int> &b)
{
return a.size() < b.size();
}
vector<vector<int>> Subsets(vector<int> data)
{
vector<vector<int>> result;
if (data.size() <= 0)
return result;
int length = data.size();
int num = pow(2, length);
int num1 = pow(2, length - 1);
sort(data.begin(), data.end());
for (int i = 0; i < num; i++)
{
vector<int> path;
if (i == 0)
{
result.push_back(path);
continue;
}
for (int j = 0; j < length; j++)
{
int temp = num1;
temp = temp >>= j;
if (i&temp)
{
path.push_back(data[j]);
}
}
result.push_back(path);
}
sort(result.begin(), result.end(), comp);
auto it = unique(result.begin(), result.end());
result.resize(distance(result.begin(), it));
return result;
}
int main()
{
int a[3] = { 1, 2, 2 };
vector<int> data(begin(a), end(a));
vector<vector<int>> res = Subsets(data);
for (int i = 0; i < res.size(); i++)
{
if (res[i].size() == 0)
cout << "[]";
for (int j = 0; j < res[i].size(); j++)
cout << res[i][j] << " ";
cout << endl;
}
}