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, ifS=[1,2,3]
, A solution is:
[[3], [1], [2], [, 3], [], [], [], []
Thought: Read sequentially. Take each subset in the front and put the number of positions behind it as a new subset.
class Solution {public: vector<vector<int> > subsets(vector<int> &S) { sort(S.begin(), S.end()); vector<vector<int> > vec(1); for(size_t id = 0; id < S.size(); ++id) { int n = vec.size(); while(n-- > 0) { vec.push_back(vec[n]); vec.back().push_back(S[id]); } } return vec; }};
Subsets II
Given a collection of integers that might contain duplicates,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, ifS=[1,2,2]
, A solution is:
[2], [1], [, 2], [], [], []
Thought: after sorting, follow the 1 method. However, if the preceding number is the same as the current number, read only each subset containing the preceding number and put itself behind it as a new subset.
class Solution {public: vector<vector<int> > subsetsWithDup(vector<int> &S) { sort(S.begin(), S.end()); vector<vector<int> > vec(1); size_t prePos, endTag; prePos = endTag = 0; for(size_t id = 0; id < S.size(); ++id) { if(id > 0 && S[id] != S[id-1]) endTag = 0; else endTag = prePos; size_t n = vec.size(); prePos = n; while(n > endTag) { --n; vec.push_back(vec[n]); vec.back().push_back(S[id]); } } return vec; }};
42. subsets & subsets II