【Leetcode】【Medium】Subsets II
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.
- The 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], [] ]
解题:
先对S进行排序,然后继续按照Subsets I的思路,
由于出现了重复元素,需要分别考虑:
当出现的数字和上一个数字不同,保持原返回队列不变,对新出现的数字,分别插入已有数组的后面,形成新数组,加入返回值队列中;此时记录形成的新数组个数X;
当出现的数字和上一个数字相同,保持原返回队列不变,从原返回队列的后方遍历X个已有数组,对这X个数组插入这个相同的数字,形成新数组,加入返回队列中;X值不变;
代码:
1 class Solution { 2 public: 3 vector<vector<int> > subsetsWithDup(vector<int> &S) { 4 sort(S.begin(), S.end()); 5 vector<vector<int> > ret; 6 ret.push_back(vector<int> ()); 7 int duplicate_record = 0; 8 9 for (int i = 0; i < S.size(); ++i) { 10 int pre_size = ret.size(); 11 12 if (i==0 || S[i] != S[i-1]) { 13 for (int j = 0; j < pre_size; ++j) { 14 vector<int> new_item(ret[j]); 15 new_item.push_back(S[i]); 16 ret.push_back(new_item); 17 } 18 duplicate_record = ret.size() / 2; 19 20 } else if (S[i] == S[i-1]) { 21 for (int j = pre_size - 1; j >= pre_size - duplicate_record; --j) { 22 vector<int> new_item(ret[j]); 23 new_item.push_back(S[i]); 24 ret.push_back(new_item); 25 } 26 } 27 28 } 29 30 return ret; 31 } 32 };