42. subsets & subsets II

Source: Internet
Author: User
Subsets

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], [], [], [], []
Thought: Read sequentially. Take each subset in the front and put the number of positions behind it as a new subset.
class Solution {public:    vector<vector<int> > subsets(vector<int> &S) {        sort(S.begin(), S.end());        vector<vector<int> > vec(1);        for(size_t id = 0; id < S.size(); ++id) {            int n = vec.size();            while(n-- > 0) {                vec.push_back(vec[n]);                vec.back().push_back(S[id]);            }        }        return vec;    }};

 

Subsets II

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, ifS=[1,2,2], A solution is:

[2], [1], [, 2], [], [], []
Thought: after sorting, follow the 1 method. However, if the preceding number is the same as the current number, read only each subset containing the preceding number and put itself behind it as a new subset.
class Solution {public:    vector<vector<int> > subsetsWithDup(vector<int> &S) {        sort(S.begin(), S.end());        vector<vector<int> > vec(1);        size_t prePos, endTag;        prePos = endTag = 0;        for(size_t id = 0; id < S.size(); ++id) {            if(id > 0 && S[id] != S[id-1]) endTag = 0;            else endTag = prePos;            size_t n = vec.size();            prePos = n;            while(n > endTag) {                --n;                vec.push_back(vec[n]);                vec.back().push_back(S[id]);            }        }        return vec;    }};

 

















42. subsets & 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.