"One Day together Leetcode" #78. Subsets

Source: Internet
Author: User

One Day together Leetcode

This series of articles has all been uploaded to my github address: Zeecoder ' s GitHub
You are welcome to follow my Sina Weibo, my Sina Weibo blog
Welcome reprint, Reprint please indicate the source

(i) Title

Given a set of distinct integers, nums, 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 nums = [A/b], a solution is:

[
[3],
[1],
[2],
[A],
[1,3],
[2,3],
[+],
[]
]

(ii) Problem solving

The main idea: given a set of numbers, calculate all of its subsets

There are several points to note:

1. Subsets cannot be duplicated

2. The number in a subset needs to be arranged in a non-descending order

Problem solving: Consider using a bitwise operation to simulate all permutations and combinations. Take the number set size equal to 3 for example:

The full array of 3-bit binaries is: 000,001,010,011,100,101,111

With this all-in arrangement, the subset is selected for 1, and 0 is not selected. It's easy to get all the subsets

classSolution { Public: vector<vector<int>>Subsets ( vector<int>& Nums) {Longn =POW(2, Nums.size ());//number of digits to get the full rank maximum valueSort (Nums.begin (), Nums.end ());//Because the number of subsets needs to be arranged in a non-descending order, the set is sorted first         vector<vector<int>>Ret for(Longi =0; I < n; i++) { vector<int>Tempset; for(intj =0; J < Nums.size (); j + +) {if((I&GT;&GT;J) &1==1)//Determine if each bit is 1{Tempset.push_back (nums[j]);        }} ret.push_back (Tempset); }returnRet }};

"One Day together 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.