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:
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>>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