2013.12.27 02:47
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], [] ]
Solution:
This problem is a variation from the problem "Subsets". This time the set can contain some duplicates, actually a "multiset".
My solution is stil by DFS. It doesn't seem to matter if the given data set is a strict set or multiset.
Time complexity is O(2^n), space complexity is O(n), where n is the number of elements in the set.
Accepted code:
1 // 1RE, 1AC, good~ 2 #include <algorithm> 3 #include <vector> 4 using namespace std; 5 6 class Solution { 7 public: 8 vector<vector<int> > subsetsWithDup(vector<int> &S) { 9 // IMPORTANT: Please reset any member data you declared, as 10 // the same Solution instance will be reused for each test case. 11 int i, j, n; 12 13 n = result.size(); 14 for(i = 0; i < n; ++i){ 15 result[i].clear(); 16 } 17 result.clear(); 18 19 sort(S.begin(), S.end()); 20 n = S.size(); 21 num.clear(); 22 count.clear(); 23 i = 0; 24 while(i < n){ 25 j = i + 1; 26 while(j < n && S[i] == S[j]){ 27 ++j; 28 } 29 num.push_back(S[i]); 30 count.push_back(j - i); 31 i = j; 32 } 33 n = num.size(); 34 arr.clear(); 35 dfs(0, n); 36 37 return result; 38 } 39 private: 40 vector<int> num; 41 vector<int> count; 42 vector<vector<int>> result; 43 vector<int> arr; 44 45 void dfs(int idx, int n) { 46 if(idx == n){ 47 result.push_back(arr); 48 // 1RE here, stop $idx from going out of range. 49 return; 50 } 51 52 int i, j; 53 for(i = 0; i <= count[idx]; ++i){ 54 for(j = 0; j < i; ++j){ 55 arr.push_back(num[idx]); 56 } 57 dfs(idx + 1, n); 58 for(j = 0; j < i; ++j){ 59 arr.pop_back(); 60 } 61 } 62 } 63 };