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());
vector<vector<int> > res;
vector<int> path;
dfs(S, 0, path, res);
return res;
}
void dfs(const vector<int> &s, int start, vector<int> &path, vector<vector<int> > &res) {
if (start == s.size()) {
res.push_back(path);
return ;
}
for (int i = start; i < s.size(); i++) {
//dfs(s, i+1, path, res);
path.push_back(s[i]);
dfs(s, i+1, path, res);
path.pop_back();
}
res.push_back(path);
return ;
}
};
本文介绍了一种生成给定整数集合所有可能子集的算法。该算法确保子集中元素按非递减顺序排列且不包含重复子集。通过深度优先搜索实现,详细展示了如何为输入[1,2,3]生成所有子集。
1350

被折叠的 条评论
为什么被折叠?



