题目要求:
Given a set of distinct integers, S, return all possible subsets.
Note:
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 > subsets(vector &S) {
vector > ans;
vector 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& str, vector >& ans, vector& 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();
}
}
};