Subsets and Subsets II (回溯,DFS,组合问题)
2014-11-24 10:15
337 查看
Givenasetofdistinctintegers,S,returnallpossiblesubsets.
Note:
Elementsinasubsetmustbeinnon-descendingorder.
Thesolutionsetmustnotcontainduplicatesubsets.
Forexample,
IfS=
我的分析图:
Givenacollectionofintegersthatmightcontainduplicates,S,returnallpossiblesubsets.
Note:
Elementsinasubsetmustbeinnon-descendingorder.
Thesolutionsetmustnotcontainduplicatesubsets.
Forexample,
IfS=
Note:
Elementsinasubsetmustbeinnon-descendingorder.
Thesolutionsetmustnotcontainduplicatesubsets.
Forexample,
IfS=
[1,2,3],asolutionis:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] 该题和Combinations很类似,只不过是k需要从0到size中取值。
classSolution{ private: vector<vector<int>>res; vector<int>s; public: voidtra(intk,intstart,intdep,vector<int>temp) { if(dep==k){ res.push_back(temp); return; } for(inti=start;i<s.size();++i){ temp.push_back(s[i]); tra(k,i+1,dep+1,temp);//是i+1,而不是start+1 temp.erase(temp.end()-1); } } vector<vector<int>>subsets(vector<int>&S){ s=S; sort(s.begin(),s.end()); vector<int>temp; for(intk=0;k<=s.size();++k){ tra(k,0,0,temp); } returnres; } };
我的分析图:
Subsets2
Givenacollectionofintegersthatmightcontainduplicates,S,returnallpossiblesubsets.
Note:
Elementsinasubsetmustbeinnon-descendingorder.
Thesolutionsetmustnotcontainduplicatesubsets.
Forexample,
IfS=
[1,2,2],asolutionis:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
classSolution{
private:
vector<vector<int>>res;
vector<int>s;
public:
voidtra(intk,intstart,intdep,vector<int>temp)
{
if(dep==k){
for(inti=0;i<res.size();++i)
{
if(res[i]==temp)return;
}
res.push_back(temp);
return;
}
for(inti=start;i<s.size();++i){
temp.push_back(s[i]);
tra(k,i+1,dep+1,temp);
temp.erase(temp.end()-1);
}
}
vector<vector<int>>subsetsWithDup(vector<int>&S){
s=S;
sort(s.begin(),s.end());
vector<int>temp;
res.push_back(temp);
for(intk=1;k<=s.size();++k){
tra(k,0,0,temp);
}
returnres;
}
};
相关文章推荐
- hdu 1027 Ignatius and the Princess II【dfs 排列组合】
- poj 1321 棋盘问题 DFS+回溯 回溯学习
- POJ2531 Network Saboteur DFS组合问题 || 随机算法
- 【LeetCode】N-Queens II N皇后问题 回溯法
- poj 1321 棋盘问题(dfs,回溯)
- POJ 1321 棋盘问题(DFS回溯)
- POJ 1321 棋盘问题(DFS+回溯)
- poj 1321 棋盘问题(DFS+回溯)
- [leetcode 78 & 90, Medium] Subsets I and II
- LeetCode题解:Subsets I and II
- hdu 2553 N皇后问题(DFS+回溯)
- 深度搜索与回溯方法不同点 Difference between DFS and Backtracking
- 回溯法之排列组合问题
- 回溯算法之 幂集问题(组合问题)
- Leetcode Subsets II 有重复元素的组合
- 回溯实现组合问题
- 回溯法解组合问题——硬币问题
- 八皇后问题 DFS,回溯剪枝 //http://poj.grids.cn/practice/2698
- hdu1027 Ignatius and the Princess II(排列问题)
- LeetCode | Best Time to Buy and Sell Stock II(股票购买抛售问题II)