题目描述
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], [] ]
分析:递归的解法,相当于一种深度优先搜索,参见网友JustDoIt的博客,由于原集合每一个数字只有两种状态,要么存在,要么不存在,那么在构造子集时就有选择和不选择两种情况,所以可以构造一棵二叉树,左子树表示选择该层处理的节点,右子树表示不选择,最终的叶节点就是所有子集合,树的结构如下:
[]
/ \
/ \
/ \
[1] []
/ \ / \
/ \ / \
[1 2] [1] [2] []
/ \ / \ / \ / \
[1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []
class Solution {
public:
static bool setCmp(vector<int> a, vector<int> b) {
if (a.size() != b.size()) {
return a.size() < b.size();
} else {
for (vector<int>::size_type i = 0; i < a.size(); ++i) {
if (a[i] != b[i]) {
return a[i] < b[i];
}
}
}
return true;
}
void dfs(vector<vector<int> >& sets, vector<int>& temp, vector<int>& S, int pos) {
sets.push_back(temp);
for (vector<int>::size_type i = pos; i < S.size(); ++i) {
temp.push_back(S[i]);
dfs(sets, temp, S, i + 1);
temp.pop_back();
}
}
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > sets;
vector<int> temp;
sort(S.begin(), S.end());
dfs(sets, temp, S, 0);
sort(sets.begin(), sets.end(), setCmp);
return sets;
}
};
其他具体解法可以参考: https://www.cnblogs.com/grandyang/p/4309345.html