LeetCode: Subsets

Source: Internet
Author: User

Given a set of distinct integers,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,

IfS=[1,2,3], A solution is:


[[3], [1], [2], [, 3], [], [], [], [], [] solutions: because the number in the S set is different, there must be 2 ^ n subsets. It is estimated that the n value in the background data should not be greater than 32, so we can use the binary value of an integer to indicate whether a number appears in the set and then enumerate it. solution code:
class Solution {public:    vector
  
    > subsets(vector
   
     &S)     {        int n = S.size();        sort(S.begin(),S.end());        vector
    
      > res;        for (int i = 0; i < 1 << n; ++i)        {            vector
     
       vec ;            int tmp = i , cnt = 0 ;            while (tmp)            {                if (tmp & 1)                    vec.push_back(S[cnt]);                tmp >>= 1 , ++cnt ;            }            res.push_back(vector
      
       (vec.begin(),vec.end()));        }        return res;    }};
      
     
    
   
  


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.