标签:
Given a set of distinct integers, S, return all possible subsets.
Note:
For example,
If S = [1,2,3]
,
a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]题意:求数组子集。
思路:一个dfs,取与不取;一个是二进制可以代表所有的子集。
class Solution { public: vector<vector<int> > ans; void subCal(vector<int> &S, int cur, vector<int> v) { if (cur == S.size()) { ans.push_back(v); return; } subCal(S, cur+1, v); v.push_back(S[cur]); subCal(S, cur+1, v); } vector<vector<int> > subsets(vector<int> &S) { vector<int> v; sort(S.begin(), S.end()); subCal(S, 0, v); return ans; } };
class Solution { public: vector<vector<int> > subsets(vector<int> &S) { sort(S.begin(), S.end()); int n = S.size(); int Max = 1<<n; vector<vector<int> > ans; for (int i = 0; i < Max; i++) { vector<int> tmp; int cur = i; int indx = 0; while (cur > 0) { if (cur & 1) tmp.push_back(S[indx]); indx++; cur = cur >> 1; } ans.push_back(tmp); } return ans; } };
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/44925791