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 manipulationIdea: On the basis of combinations, direct adjustment k, is k from 0 to N can realize the function of subset.
classSolution {Vector<vector<int> >M_res; Vector<int>M_array; Public: voidDfsintNintKintStart, vector<int> &inch) { if(k = =m_array.size ()) {M_res.push_back (M_array); return; } for(inti = start; I < n; i++) {M_array.push_back (inch[i]); DFS (n, K, I+1,inch); M_array.pop_back (); } } voidCombineintNintElementnum, vector<int> &inch) {DFS (n, Elementnum,0,inch); } Public: Vector<vector<int> > Subsets (vector<int> &S) {sort (S.begin (), S.end ()); for(inti =0; I <= s.size (); i++) {Combine (s.size (), I, S); M_array.clear (); } returnM_res; }};
Second: You can also direct DFS, for each element has 2 choices, join or not join, in fact, DFS is the key is in the DFS loop is the scope of each element can be selected, for this topic, is either to join, or not to join, you can use for (i=0;i<2;i++ Said is actually the standard backtracking subset tree problem.
classSolution {Vector<vector<int> >M_res; Vector<int>M_array; Public: voidDfsintDEP, vector<int> &S) {if(DEP = =s.size ()) {M_res.push_back (M_array); return ; }#if0 for(inti =0; i<2; i++) { //contain the element if(i = =0) {m_array.push_back (S[DEP]); DFS (DEP+1, S); M_array.pop_back (); } //don ' t contain the element ElseDfs (DEP+1, S); }#else //contain the elementM_array.push_back (S[DEP]); DFS (DEP+1, S); M_array.pop_back (); //don ' t contain the elementDFS (DEP +1, S);#endif} vector<vector<int> > Subsets (vector<int> &S) {sort (S.begin (), S.end ()); DFS (0, S); returnM_res; }};
Train of thought 3. Bit-vector method, and the above method is no essential difference
//Leetcode, subsets//position vector method, deep search, Time complexity O (2^n), Space complexity O (n)classSolution { Public: Vector<vector<int> > Subsets (vector<int> &S) {sort (S.begin (), S.end ());//Êä³öòªçóóððòvector<vector<int> >result; Vector<BOOL> Selected (S.size (),false); Subsets (S, selected,0, result); returnresult; } Private: Static voidSubsets (Constvector<int> &s, vector<BOOL> &selected,intStep, Vector<vector<int> > &result) { if(Step = =s.size ()) {Vector<int>subset; for(inti =0; I < s.size (); i++) { if(Selected[i]) subset.push_back (s[i]); } result.push_back (subset); return; } //not selected S[step]Selected[step] =false; Subsets (S, selected, step+1, result); //Choose S[step]Selected[step] =true; Subsets (S, selected, step+1, result); } };
[Leetcode] Subsets