Leetcode Note: Subsets
I. Description
Given a set of distinct integers, nums, 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,
Ifnums = [1,2,3], A solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]
Ii. Question Analysis
The general idea of this question is to give a set and find all the subsets of the Set (the so-called subset is the set that contains a part of the elements in the original set ). You can use DFS recursive nesting. TotalNLayer, time complexity isO(2^N). My approach is to use bitwise operations,NElement arrays have2^NSo this question can be converted into an array element combination. Use oneNBitwise binary represents an arraynumsWhether or not each subscript1Indicates that the element corresponding to the current subscript appears in the combination. Otherwise, the current subscript element is not selected, and the time complexity is alsoO(2^N).
Iii. Sample Code
// Method 1, bitwise operation class Solution {public: vector
> Subsets (vector
& Nums) {sort (nums. begin (), nums. end (); int n = nums. size (); int MAX = 1 <n; vector
> Result; for (int I = 0; I <MAX; ++ I) {vector
Temp; int index = 0; int j = I; while (j> 0) {if (j & 1) // The bitwise of the binary number is 1, it indicates that this bit appears in the order temp. push_back (nums [index]); j = j> 1; // shift multiple times to determine whether the index is 1 + +; // Add 1} result to the subscript of nums. push_back (temp);} return result ;}};
// Method 2, DFS # include
# Include
# Include using namespace std; class Solution {public: vector
> Result; vector
Temp; vector
> Subsets (vector
& Nums) {if (nums. empty () return result; sort (nums. begin (), nums. end (); dfs (0, temp, nums); return result;} private: void dfs (int k, vector
Temp, vector
Nums) {result. push_back (temp); for (int I = k; I <nums. size (); ++ I) {temp. push_back (nums [I]); dfs (I + 1, temp, nums); temp. pop_back ();}}};
Iv. Summary
From the submitted results, there seems to be a faster algorithm.