【题目描述】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) {
vector<vector<int> > ans;
vector<int> path;
ans.push_back(path);
sort(S.begin(), S.end());
for(size_t i = 1; i <= S.size(); ++i){
path.clear();
DFS(S, ans, path, 0, 0, i);
}
return ans;
}
void DFS(vector<int>& str, vector<vector<int> >& ans, vector<int>& path,
int start, int count, int max_count){
if(count == max_count){
ans.push_back(path);
return ;
}
for(size_t i = start; i < str.size(); ++i){
path.push_back(str[i]);
DFS(str, ans, path, i + 1, count + 1, max_count);
path.pop_back();
}
}
};