题目
Given a collection of integers that might contain duplicates, 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,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
分析
求带有重复元素的序列的全子集;
用动态规划的思想,逐个向前i-1的元素的子集中添加第i个元素,添加时需要判重,若已存在,则不添加。
AC代码
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int> > ret(1, vector<int>());
if (nums.empty())
return ret;
sort(nums.begin(), nums.end());
int size = nums.size();
for (int i = 0; i < size; ++i)
{
ret = subSets(ret, nums, i);
}
return ret;
}
vector<vector<int> > subSets(vector<vector<int> > &ret, vector<int> &nums, int &idx)
{
vector<int> tmp;
int count = ret.size();
//对于每一个已有子集合,加入新元素
for (int i = 0; i < count; ++i)
{
//当前集合
tmp = ret[i];
tmp.push_back(nums[idx]);
if (find(ret.begin(), ret.end(), tmp) != ret.end())
continue;
ret.push_back(tmp);
}//for
return ret;
}
};