Subsets
Given a set of distinct integers, S, 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,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
思路:构造子集有三种方法,分别是:1) DFS 和排列的思路类似,只是return的时候没有条件,并且for循环的边界是(当前已经出去的元素的下一个开始)
2) 每个元素或者选或者不选,共有2^N种可能性,然后进行递归,同样是DFS
3) 位运算的方式
后续将2)和3)的方式进行补充
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: void mySubSets(vector<vector<int> > & ans, vector<int> & S, vector<int> & A){ ans.push_back(A); for(int i = 0; i < S.size();i++){ if (A.size() && S[i] <= A[A.size() -1]){ continue; } A.resize(A.size() + 1); A[A.size() -1] = S[i]; mySubSets(ans,S,A); A.resize(A.size() -1); } } vector<vector<int> > subsets(vector<int> &S) { vector<int> A; vector<vector<int> > ans; if (S.empty()){ return ans; } sort(S.begin(),S.end()); mySubSets(ans,S,A); return ans; } }; using namespace std; int main(int argc, char *argv[]) { int a[] = {1,2}; vector<int> v(a,a+2); Solution sol; sol.subsets(v); }