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], []]
思路:
和一样,只是这里原容器中有重复的元素,于是就增加一个去重。去重的方法我用的还是与leetcode上的另一个一样,开辟一个数组记录当前元素是否使用过。如果当前元素等于前一个元素,且前一个元素没有使用,那么当前元素就不能使用。
class Solution {public: vector> res; void dfs(vector &s, bool used[], int index, vector tmp) { if(index==s.size()) { res.push_back(tmp); return; } dfs(s, used, index+1, tmp); if(!used[index]) { if(index!=0 && s[index]==s[index-1] && !used[index-1]) return; used[index] = true; tmp.push_back(s[index]); dfs(s, used, index+1, tmp); used[index] = false; } } vector > subsetsWithDup(vector &s) { sort(s.begin(), s.end()); vector tmp; int n = s.size(); bool *used = new bool [n]; memset(used, false, n); dfs(s, used, 0, tmp); return res; }};