Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
For example,
If S = [1,2,2]
, a solution
is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
这个题很subsets这个题一样,不过这里允许给出的集合中含有重复元素,对于这个条件之需要加一个判断条件就可以了,其余代码和Subsets都一样。
class Solution { public: vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int> > ret; sort(S.begin(), S.end()); helper(0, S, vector<int>(), ret); return ret; } void helper(int start, const vector<int>& S, vector<int> part, vector<vector<int> >& ret){ if(start == S.size()) return; if(start == 0) ret.push_back(part); for(int i=start; i<S.size(); ++i){ // 这里加了个判断,就可以避免重复组合 if(i>start && S[i] == S[i-1]) continue; part.push_back(S[i]); ret.push_back(part); helper(i+1, S, part, ret); part.pop_back(); } } };
[LeetCode] Subsets II [32],布布扣,bubuko.com
原文地址:http://blog.csdn.net/swagle/article/details/30221841