Problem:
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 manipulationTest instructions: Given an array, find all its subsets, including the empty set
Thinking:
(1) 77 has already used the DFS to find the number of sets of all subsets of K, where the value range k is 1~n,n array length
Specific reference: http://blog.csdn.net/hustyangju/article/details/44974825
Code
Class Solution {private: vector<vector<int> > ret; Vector<int> tmp;public: vector<vector<int> > Subsets (vector<int> &S) { Ret.clear (); unsigned int n=s.size (); if (n==0) return ret; Sort (S.begin (), S.end ()); Tmp.clear (); Ret.push_back (TMP); for (int k=1;k<=n;k++) { tmp.resize (k); DFS (0,n,s,k,0); } return ret; } Protected: void dfs (int dep, int n, vector<int> &s,int k,int start) { if (dep==k) { Ret.push_back (TMP); return; } for (int i=start;i<n;i++) { tmp[dep]=s[i]; DFS (dep+1,n,s,k,i+1);}} ;
Another Dfs method:
Class Solution {private: vector<vector<int> > ret;public: void dfs (int dep, int maxdep, vector< Int> &num, vector<int> A, int start) { ret.push_back (a); if (dep = = MAXDEP) return; for (int i = start; I < num.size (); i++) { vector<int> B (a); B.push_back (Num[i]); DFS (DEP + 1, MAXDEP, num, B, i + 1); } } vector<vector<int> > Subsets (vector<int> &s) { sort (s.begin (), S.end ()); Ret.clear (); Vector<int> A; DFS (0, s.size (), S, a, 0); return ret; }};
Leetcode | | 78, subsets