LeetCode 90: Subsets II
Given a collection of integers that might contain duplicates, nums, 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,
Ifnums =[1,2,2], A solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], []]
Subscribeto see which companies asked this question
This question has repeated elements, but in essence, it is similar to the question and can be handled in a similar way:
Class Solution {public: vector
> SubsetsWithDup (vector
& Nums) {vector
> Ans (1, vector
(); Sort (nums. begin (), nums. end (); int pre_size = 0; for (int I = 0; I <nums. size (); I ++) {int n = ans. size (); for (int j = 0; j <n; j ++) // The second for loop is used to obtain all subsets containing nums [I] {if (I = 0 | nums [I]! = Nums [I-1] | j> = pre_size) {ans. push_back (ans [j]); // re-insert an existing subset of ans at the end. back (). push_back (nums [I]); // Add nums [I]} pre_size = n;} return ans ;}};