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],
[]
]
思路:这道题在Subsets基础上,添加了重复元素,然而在最后的结果当中不能有重复的vector出现,也就是在组合这些整数的时候要加一些限制条件。
class Solution { public: void find(vector<vector<int> > &result,vector<int> &S,vector<int> data,int index) { result.push_back(data); for(int i=index;i<S.size();i++) { if(i!=index&&S[i]==S[i-1]) continue; data.push_back(S[i]); find(result,S,data,i+1); data.pop_back(); } } vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int> > result; vector<int> data; result.clear(); if(S.empty()) return result; sort(S.begin(),S.end()); find(result,S,data,0); return result; } };