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 =
If S =
[1,2,3]
, a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
slove:
通过位标记来记录某个值是否参与到此次组合。
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > ret;
std::sort(S.begin(), S.end());
run(ret, S);
return ret;
}
void run(vector<vector<int> >&ret, vector<int> str) {
vector<int> res;
ret.push_back(res);
int len = str.size();
for(int i = 1; i < (1<<len); ++ i) {
for(int j = 0; j < len; ++ j) {
if(i & (1 << j)) {
res.push_back(str.at(j));
}
}
ret.push_back(res);
res.clear();
}
}
};
坑:
输入向量不一定是有序的。
没有评论:
发表评论