C++ solution and explanation
To solve this problem, it is helpful to first think how many subsets are there. If there is no duplicate element, the answer is simply 2^n, where n is the numbe
To solve this problem, it is helpful to first think how many subsets are there. If there is no duplicate element, the answer is simply 2^n, where n is the number of elements. This is because you have two choices for each element, either putting it into the subset or not. So all subsets for this no-duplicate set can be easily constructed:\nnum of subset\n\n -  (1        to 2^0) empty set is the first subset\n -  (2^0+1 to 2^1) add the first element into subset from (1)\n -  (2^1+1 to 2^2) add the second element into subset (1 to 2^1)\n -  (2^2+1 to 2^3) add the third element into subset (1 to 2^2)\n - ....\n -  (2^(n-1)+1 to 2^n) add the nth element into subset(1 to 2^(n-1))\n\nThen how many subsets are there if there are duplicate elements? We can treat duplicate element as a spacial element. For example, if we have duplicate elements (5, 5), instead of treating them as two elements that are duplicate, we can treat it as one special element 5, but this element has more than two choices: you can either NOT put it into the subset, or put ONE 5 into the subset, or put TWO 5s into the subset. Therefore, we are given an array (a1, a2, a3, ..., an) with each of them appearing (k1, k2, k3, ..., kn) times, the number of subset is (k1+1)*(k2+1)*...(kn+1). We can easily see how to write down all the subsets similar to the approach above.\n\n        class Solution {\n    public:\n        vector<vector<int> > subsetsWithDup(vector<int> &S) {\n            vector<vector<int> > totalset = {{}};\n            sort(S.begin(),S.end());\n            for(int i=0; i<S.size();){\n                int count = 0; // num of elements are the same\n                while(count + i<S.size() && S[count+i]==S[i])  count++;\n                int previousN = totalset.size();\n                for(int k=0; k<previousN; k++){\n                    vector<int> instance = totalset[k];\n                    for(int j=0; j<count; j++){\n                        instance.push_back(S[i]);\n                        totalset.push_back(instance);\n                    }\n                }\n                i += count;\n            }\n            return totalset;\n            }\n    };
[]