[LeetCode]Subsets II
2013-06-01 09:46
127 查看
class Solution { //because Elements in a subset must be in non-descending order. //so if we sort the vector first. //If we choose an elem[i] into subset, then we should choose elem[j](i<j<n) into the subset, //repeat this until there is no element left any more. //But note: in the same level we can not choose multiple same elements as the new heads of the next subset. void DFS(vector<int>& S, int curPos, vector<int>& oneSubset, vector<vector<int>>& allSubset) { allSubset.push_back(oneSubset); for (int i = curPos; i < S.size(); ++i) { if(i != curPos && S[i] == S[i-1]) continue; oneSubset.push_back(S[i]); DFS(S, i+1, oneSubset, allSubset); oneSubset.pop_back(); } } public: vector<vector<int> > subsetsWithDup(vector<int> &S) { // Start typing your C/C++ solution below // DO NOT write int main() function sort(S.begin(), S.end()); vector<int> oneSubset; vector<vector<int>> allSubset; DFS(S, 0, oneSubset, allSubset); return allSubset; } };
second time
class Solution { public: void subsetUtil(vector<int>& S, vector<bool>& used, int curIdx, vector<int>& curPath, vector<vector<int> >& allPath) { if(curIdx == S.size()) { allPath.push_back(curPath); return ; } subsetUtil(S, used, curIdx+1, curPath, allPath); if(curIdx >= 1 && S[curIdx] == S[curIdx-1] && used[curIdx-1] == false) return; used[curIdx] = true; curPath.push_back(S[curIdx]); subsetUtil(S, used, curIdx+1, curPath, allPath); curPath.pop_back(); used[curIdx] = false; } vector<vector<int> > subsetsWithDup(vector<int> &S) { // Start typing your C/C++ solution below // DO NOT write int main() function sort(S.begin(), S.end()); vector<bool> used(S.size(), false); vector<vector<int> > allPath; vector<int> curPath; subsetUtil(S, used, 0, curPath, allPath); return allPath; } };
相关文章推荐
- LeetCode---Subsets II
- LeetCode 90:Subsets II
- Leetcode--Subsets II
- leetcode - Subsets II
- [LeetCode]Subsets II生成组合序列
- leetcode 90: Subsets II
- Leetcode: Subsets II
- [LeetCode]Subsets II
- LeetCode Subsets II
- LeetCode Subsets II
- [leetcode][回溯] Subsets II
- Leetcode#90 Subsets II
- leetcode[90]Subsets II
- LEETCODE: Subsets II
- [C++]LeetCode: 64 Subsets II
- LeetCode之Subsets II
- [leetCode] Subsets II
- [leetcode]Subsets II
- [leetcode]Subsets II
- [Leetcode]Subsets II