给定一个可能具有重复数字的列表,返回其所有可能的子集
样例
如果S = [1,2,2],一个可能的答案为:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
注意
子集中的每个元素都是非降序的
两个子集间的顺序是无关紧要的
解集中不能包含重复子集
class Solution {
public:
/**
* @param S: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
vector<vector<int> > subsetsWithDup(const vector<int> &S) {
// write your code here
vector<int> K(S);
int n = K.size();
sort(K.begin(), K.end());
vector<vector<int> > result;
vector<int> buf;
visit(K, 0, n, buf, result);
return result;
}
private:
void visit(const vector<int> &S, int pos, int n, vector<int> &buf,
vector<vector<int> > &result)
{
if (pos >= n)
{
result.push_back(buf);
return;
}
int next = pos+1;
while (next < n && S[next] == S[pos])
{
next++;
}
visit(S, next, n, buf, result);
for (int i = pos; i < next; i++)
{
buf.push_back(S[i]);
visit(S, next, n, buf, result);
}
int len = next-pos;
while (len > 0)
{
buf.pop_back();
len--;
}
}
};