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], [] ]
思路
在上一题的基础上,因为数组元素可能有重复,所以在递归的时候要避免如果有几个相同的元素,在这几个元素中间选择时只能往上增加,不能跳跃的选择。因此增加第24行到第29行的判断。
1 vector<vector<int> > result; 2 vector<int> tmp; 3 void initialize(vector<int> &S){ 4 tmp.clear(); 5 result.clear(); 6 int n = S.size(); 7 int i,j; 8 int t; 9 for(i = 0; i < n-1; i++){ 10 for(j = 0; j <= n-2-i; j++){ 11 if(S[j] > S[j+1]){ 12 t = S[j]; 13 S[j] = S[j+1]; 14 S[j+1] = t; 15 } 16 } 17 } 18 } 19 void getSubsets(vector<int> &S, int start, int end){ 20 if(end == start){ 21 result.push_back(tmp); 22 return; 23 } 24 if(tmp.empty()) 25 getSubsets(S, start+1, end); 26 else{ 27 if(S[start] > tmp[tmp.size()-1]) 28 getSubsets(S, start+1, end); 29 } 30 tmp.push_back(S[start]); 31 getSubsets(S, start+1, end); 32 tmp.pop_back(); 33 } 34 vector<vector<int> > subsetsWithDup(vector<int> &S) { 35 // Note: The Solution object is instantiated only once and is reused by each test case. 36 int n = S.size(); 37 initialize(S); 38 getSubsets(S, 0, n); 39 return result; 40 }