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], [] ]
思考:最后还是按上一题的思路来k=0:n
class Solution {
private:
vector<vector<int> > res;
vector<int> ans;
public:
void DFS(vector<int> S,int n,int start,int dep,int k)
{
if(dep==k)
{
res.push_back(ans);
return;
}
for(int i=start;i<n-k+1;i++)
{
ans.push_back(S[i+dep]);
DFS(S,n,i,dep+1,k);
ans.pop_back();
}
}
vector<vector<int> > subsets(vector<int> &S) {
res.clear();
ans.clear();
int n=S.size();
sort(S.begin(),S.end());
for(int k=0;k<=n;k++)
{
DFS(S,n,0,0,k); //上一题的k
}
return res;
}
};
second time:
class Solution {
public:
void DFS(vector<vector<int> > &res, vector<int> &ans, vector<int> &S, int dep, int start)
{
res.push_back(ans);
if(dep == S.size()) return;
for(int i = start; i < S.size(); ++i)
{
ans.push_back(S[i]);
DFS(res, ans, S, dep + 1, i + 1);
ans.pop_back();
}
}
vector<vector<int> > subsets(vector<int> &S) {
vector<vector<int> > res;
vector<int> ans;
sort(S.begin(), S.end());
DFS(res, ans, S, 0, 0);
return res;
}
};