//90. Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
res.clear();
if(nums.size()==0){
return res;
}
vector<int> s;
for(int i=0;i<nums.size();i++){
findNext(nums,0,i,s);
}
res.push_back(nums);
return res;
}
private:
vector<vector<int> > res;
//s saved 0---start-1,nums
void findNext(vector<int>& nums,int start,int k,vector<int>& s){
if(s.size()==k){
res.push_back(s);
return;
}
for(int i=start;i<nums.size();i++){
//deal with the i element
s.push_back(nums[i]);
//dela with the i+1 element
findNext(nums,i+1,k,s);
s.pop_back();
//recursuion end,when to push next,skip same value first
while(i<nums.size()-1 && nums[i]==nums[i+1] ){
i++;
}
}
return;
}
};
int main(){
int arr[]={4,4,4,1,4};
vector<int> nums(arr,arr+sizeof(arr)/sizeof(int));
vector<vector<int> > res=Solution().subsetsWithDup(nums);
for(int i=0;i<res.size();i++){
for(int j=0;j<res[i].size();j++){
cout<<res[i][j]<<" ";
}
cout<<endl;
}
return 0;
}