Leetcode -- subsets II

Source: Internet
Author: User

Problem description:

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],  []]

Analysis: to print out all non-repeated combinations, you can use a flag array to record whether the current element has been used, and then determine whether the element has been reused, the Code is as follows:

Class solution {public: void DFS (vector <int> & S, int beg, int Len, vector <int> & Mid, vector <int> & res, vector <int> & flag) {If (LEN = 0) {res. push_back (MID); return;} If (beg = S. size () return; If (beg = 0 | s [beg]! = S [beg-1] | (s [beg] = s [beg-1] & flag [beg-1] = 1 )) // select the current element {mid. push_back (s [beg]); flag [beg] = 1; DFS (S, beg + 1, len-1, mid, res, flag); flag [beg] = 0; mid. pop_back (); DFS (S, beg + 1, Len, mid, res, flag);} else // The current element {DFS (S, beg + 1, Len, mid, res, flag) ;}}vector <vector <int> subsetswithdup (vector <int> & S) {vector <int> res; int Len = S. size (); If (LEN = 0) return res; vector <int> mid; vector <int> flag (Len, 0); sort (S. begin (), S. end (); For (INT I = 0; I <= Len; ++ I) // a combination of DFS (S, 0, I, mid, res, flag );}};


Leetcode -- subsets II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.