subsets
Q:
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], [] ]
A: DFS问题。
void dfs(vector<int>& S, int step,vector<int>& sequence,vector<vector<int> >& result)
{
if(step == S.size())
{
result.push_back(sequence);
//sequence.clear(); //注意这里不要clear,因为在上层做了恢复。
return;
}
dfs(S,step+1,sequence,result); //not choose S[step]
sequence.push_back(S[step]); //choose S[step]
dfs(S,step+1,sequence,result);
sequence.pop_back(); //返回时,将sequence恢复原样!!重要
}
vector<vector<int> > subsets(vector<int> &S) {
// Start typing your C/C++ solution below
// DO NOT write int main() function>
vector<int> sequence;
vector<vector<int> > result;
sort(S.begin(),S.end());
dfs(S,0,sequence,result);
return result;
}
[second]
vector<vector<int> > subsets(vector<int> &S) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<int>> res; vector<int> path; sort(S.begin(),S.end()); //注意,先排序 construct(0,S,path,res); return res; } void construct(int pos,vector<int>& S, vector<int>& path,vector<vector<int>>& res) { if(pos==S.size()) { res.push_back(path); return; } construct(pos+1,S,path,res); path.push_back(S[pos]); construct(pos+1,S,path,res); path.pop_back(); }
浙公网安备 33010602011771号