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], [] ]Analysis:
DFS. Similar with Subsets, difference here is to remove duplicate numbers.
Java
public class Solution { List<List<Integer>> result; List<Integer> solu; public List<List<Integer>> subsetsWithDup(int[] num) { result = new ArrayList<>(); solu = new ArrayList<>(); Arrays.sort(num); getSubset(num, 0); return result; } public void getSubset(int[] num, int st){ if(solu.size()<=num.length){ result.add(new ArrayList<>(solu)); } for(int i=st;i<num.length;i++){ solu.add(num[i]); getSubset(num, i+1); solu.remove(solu.size()-1); while(i<num.length-1 && num[i]==num[i+1]) i++; } } }c++
class Solution { public: void genSubset( vector<vector<int>> &result, vector<int> &solu, vector<int> &S, int level){ for(int i=level; i<S.size(); i++){ solu.push_back(S[i]); result.push_back(solu); if(i<S.size()-1){ genSubset(result,solu,S,i+1); } solu.pop_back(); while(S[i] == S[i+1] && i<S.size()-1){ i++; } } } vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int>> result; vector<int> solu; if(S.size() == 0) return result; result.push_back(solu); sort(S.begin(), S.end()); genSubset(result, solu, S, 0); return result; } };