题目:
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);
}
};
本文介绍了一种算法,用于给定一个不重复的整数集合,返回该集合的所有可能子集。子集内的元素必须按非递减顺序排列,并且解决方案中不能包含重复的子集。以[1,2,3]为例,文章详细展示了如何通过深度优先搜索生成所有子集。
633

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



