SubsetsApr 18 '126226 / 16269
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], [] ]
class Solution { public: vector<vector<int> > subsets(vector<int> &S) { sort(S.begin(), S.end()); vector<vector<int> > res; int n = S.size(); for (int i = 0; i <= n; i++) { vector<int> a; gen(res, S, i, 0, a); } return res; } void gen(vector<vector<int> >& res, const vector<int>& s, int n, int cur, vector<int> &a) { if (a.size() == n) { res.push_back(a); return; } if (cur == s.size()) return; gen(res, s, n, cur+1, a); a.push_back(s[cur]); gen(res, s, n, cur+1, a); a.pop_back(); } };