题目:
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], [] ]
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end());
int n = S.size();
vector<int> row;
ans.clear();
dfs(0, row, n, S);
return ans;
}
private:
vector<vector<int>> ans;
//每个元素有取和不取两种选择,使用深度搜索,共2^n(n为集合大小)个子集
void dfs(int depth, vector<int> row, int n, vector<int> &S) {
if (depth == n) {
ans.push_back(row);
return;
}
dfs(depth + 1, row, n, S);
row.push_back(S[depth]);
dfs(depth + 1, row, n, S);
}
};