Subsets
Given a set of distinct integers, S, return all possible subsets.
Note:
If S =
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
If S =
[1,2,3]
, a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Thoughts:
For a set with n elements, the number of subsets is 2^n. Every element has "chosen" or "not-chosen" state, this led direct use of bit operations.
Solution:
- class Solution {
- public:
- vector<vector<int> > subsets(vector<int> &S) {
- sort(begin(S), end(S)); // ensure non-descending results
- const size_t n = S.size();
- const size_t num_sets = pow(2, n);
- vector<vector<int>> ret(num_sets);
- for(size_t bitwise = 0; bitwise < num_sets; ++bitwise)
- {
- size_t bit_chk = 1;
- for(size_t bit = 0; bit < n; ++bit)
- if ((bit_chk << bit) & bitwise)
- ret[bitwise].push_back(S[bit]);
- }
- return ret;
- }
- };
No comments:
Post a Comment