class Solution { public: vector<vector<int> > subsetsWithDup(vector<int> &S) { int len = S.size(); vector<vector<int> > res; vector<int> subset; if (len < 1) { res.push_back(subset); return res; } sort(S.begin(), S.end()); vector<int> stat; vector<int> nums; int count = 1; int cur = S[0]; int last = cur; for (int i=1; i<len; i++) { cur = S[i]; if (cur != last) { stat.push_back(count); nums.push_back(last); last = cur; count = 0; } count++; } stat.push_back(count); nums.push_back(last); dfs(nums, stat, res, subset, 0); } void dfs(vector<int> &nums, vector<int> &stat, vector<vector<int> > &res, vector<int> &subset, int k) { if (k >= nums.size()) { res.push_back(subset); return; } int cnt = stat[k]; int old = subset.size(); for (int i=0; i <= cnt; i++) { dfs(nums, stat, res, subset, k + 1); subset.push_back(nums[k]); } subset.resize(old); } };
常规dfs
第二轮:
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], [] ]
简单一些
1 class Solution { 2 private: 3 vector<vector<int> > res; 4 public: 5 vector<vector<int> > subsetsWithDup(vector<int> &S) { 6 sort(S.begin(), S.end()); 7 res.clear(); 8 9 vector<int> current; 10 dfs(S, 0, current); 11 return res; 12 } 13 void dfs(vector<int>& S, int pos, vector<int>& current) { 14 int len = S.size(); 15 if (pos == len) { 16 res.push_back(current); 17 return; 18 } 19 20 int cnt = 1; 21 int idx = pos; 22 while ((idx + 1) < len && S[idx] == S[idx + 1]) { 23 idx++, cnt++; 24 } 25 26 for (int i=0; i<=cnt; i++) { 27 dfs(S, pos + cnt, current); 28 current.push_back(S[pos]); 29 } 30 current.resize(current.size() - cnt - 1); 31 } 32 33 };
深夜来个非递归版:
// 0:30 class Solution { public: vector<vector<int>> subsetsWithDup(vector<int>& nums) { sort(nums.begin(), nums.end()); int len = nums.size(); vector<vector<int>> res(1); for (int i=0; i<len; i++) { if (i != 0 && nums[i] == nums[i - 1]) { continue; } int last_size = res.size(); int k = i; while (k < len && nums[k] == nums[i]) { k++; } for (int j=0; j<last_size; j++) { for (int c=1; c<=k - i; c++) { res.emplace_back(res[j]); for (int x=0; x < c; x++) { res[res.size() - 1].push_back(nums[i]); } } } } return res; } };