LeetCode_Subsets II
Given a collection of integers that might contain duplicates, 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,2], a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
DFS :
class Solution { public: void DFS(vector<int> &S, vector<int> &temp,int n, int size,int start) { if(n == size) { result.push_back(temp); return ; } if(n > size) return ; for(int i = start; i< len ;i++) { if(i != start && S[i] == S[i-1]) continue ; if(flag[i] == false) { flag[i] = true; temp.push_back(S[i]); DFS(S, temp, n+1, size,i+1); temp.pop_back(); flag[i] = false; } } } vector<vector<int> > subsetsWithDup(vector<int> &S) { // Start typing your C/C++ solution below // DO NOT write int main() function result.clear(); len = S.size(); flag.resize(len,false); vector<int> temp; result.push_back(temp) ; sort(S.begin(), S.end()); for(int i = 1; i <= len ; i++) DFS(S, temp,0, i,0); return result; } private: vector<vector<int> > result ; vector<bool> flag; int len; };
解释下这句:”if(i != start && S[i] == S[i-1]) continue ; 这句话保证每个循环进入的元素不会有重复。start : 保证所有的元素进入的顺序为从左往右~
重写后的代码:
class Solution { public: void DFS(vector<int> &S, vector<int> &ans, int size, int currentPos) { if(ans.size() == size ){ res.push_back(ans); return; } for(int i = currentPos; i< S.size(); ++i) { if(i != currentPos && S[i] == S[i-1]) continue; ans.push_back(S[i]); DFS(S, ans, size, i+1); ans.pop_back(); } } vector<vector<int> > subsetsWithDup(vector<int> &S) { // Start typing your C/C++ solution below // DO NOT write int main() function res.clear(); sort(S.begin(), S.end()); vector<int> emp; res.push_back(emp); for(int i = 1; i <= S.size(); ++i) { vector<int> ans; DFS(S, ans, i, 0); } return res; } private: vector<vector<int>> res; };
--------------------------------------------------------------------天道酬勤!