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], [] ]分析:求集合的所有子集问题。题目要求子集中元素非递减序排列,因此我们先要对原来的集合进行排序。原集合中每一个元素在子集中有两种状态:要么存在、要么不存在。这样构造子集的过程中每个元素就有两种选择方法:选择、不选择,因此可以构造一颗二叉树,例如对于例子中给的集合[1,2,3],构造的二叉树如下(左子树表示选择该层处理的元素,右子树不选择),最后得到的叶子节点就是子集:
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > res;
if(S.size() == 0)
return res;
vector<int> tmp;
sort(S.begin(),S.end());
find(res,S,tmp,0);
return res;
}
void find(vector<vector<int> >& res, vector<int>& S,vector<int>& tmp,int k) {
if(S.size() == k) {
res.push_back(tmp);
//return;
} else {
find(res,S,tmp,k+1);
tmp.push_back(S[k]);
find(res,S,tmp,k+1);
tmp.pop_back(); // tmp为引用类型时要pop
}
}
};
或者用排列组合的方法:
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > res;
if(S.size() == 0)
return res;
vector<int> tmp;
sort(S.begin(),S.end());
for(int k=1;k<=S.size();k++) {
tmp.clear();
find(res,S,tmp,k,0);
}
tmp.clear();
res.push_back(tmp);
return res;
}
void find(vector<vector<int> >& res, vector<int>& S,vector<int>& tmp,int k,int start) {
if(tmp.size() == k) {
res.push_back(tmp);
return;
}
for(int i= start;i<S.size();i++) {
tmp.push_back(S[i]);
find(res,S,tmp,k,i+1);
tmp.pop_back();
}
}
};