[LeetCode] 109: Subsets

来源:互联网 发布:布拉格之春 知乎 编辑:程序博客网 时间:2024/06/05 07:26
[Problem]

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],  []]
[Solution]

class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
// Note: The Solution object is instantiated only once and is reused by each test case.

// result
vector<vector<int> >res;
if(S.size() == 0)return res;

// sort
sort(S.begin(), S.end());

// generate subsets
long long total = pow(2, S.size());
for(long long i = 0; i < total; ++i){
vector<int> row;
for(int j = 0; j < S.size(); ++j){
if((i >> j) & 1 == 1){
row.push_back(S[j]);
}
}
if(find(res.begin(), res.end(), row) == res.end()){
res.push_back(row);
}
}
return res;
}
};

说明:版权所有,转载请注明出处。Coder007的博客