Leetcode | | 78, subsets

Source: Internet
Author: User

Problem:

Given a set of distinct integers, S, return all possible subsets.

Note:

    • Elements in a subset must is in non-descending order.
    • The solution set must not contain duplicate subsets.

For example,
If S = [1,2,3] , a solution is:

[  3],  [1], [2], [1,3], [+]  ,  [2,3], [up  ],  []]

Hide TagsArray backtracking Bit manipulationTest instructions: Given an array, find all its subsets, including the empty set

Thinking:

(1) 77 has already used the DFS to find the number of sets of all subsets of K, where the value range k is 1~n,n array length

Specific reference: http://blog.csdn.net/hustyangju/article/details/44974825

Code

Class Solution {private:    vector<vector<int> > ret;    Vector<int> tmp;public:    vector<vector<int> > Subsets (vector<int> &S) {    Ret.clear ();    unsigned int n=s.size ();    if (n==0)        return ret;    Sort (S.begin (), S.end ());    Tmp.clear ();    Ret.push_back (TMP);    for (int k=1;k<=n;k++)    {        tmp.resize (k);        DFS (0,n,s,k,0);    }    return ret;    } Protected:    void dfs (int dep, int n, vector<int> &s,int k,int start)    {       if (dep==k)       {           Ret.push_back (TMP);           return;       }       for (int i=start;i<n;i++)       {           tmp[dep]=s[i];           DFS (dep+1,n,s,k,i+1);}}    ;

Another Dfs method:

Class Solution {private:    vector<vector<int> > ret;public:    void dfs (int dep, int maxdep, vector< Int> &num, vector<int> A, int start)    {        ret.push_back (a);                if (dep = = MAXDEP)            return;                    for (int i = start; I < num.size (); i++)        {            vector<int> B (a);            B.push_back (Num[i]);            DFS (DEP + 1, MAXDEP, num, B, i + 1);        }    }        vector<vector<int> > Subsets (vector<int> &s) {        sort (s.begin (), S.end ());        Ret.clear ();        Vector<int> A;        DFS (0, s.size (), S, a, 0);                return ret;    }};



Leetcode | | 78, subsets

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.