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], [] ]
主要考虑去重,最简单的想法,在递归添加元素的时候,判断该元素是否已经出现过了
1 class Solution { 2 3 public: 4 5 vector<vector<int> > subsetsWithDup(vector<int> &S) { 6 7 8 9 vector<vector<int> > result; 10 11 vector<int> tmp; 12 13 sort(S.begin(),S.end()); 14 15 getSubset(result,S,0,tmp); 16 17 return result; 18 19 } 20 21 22 23 void getSubset(vector<vector<int> > &result,vector<int> &S,int index,vector<int> tmp) 24 25 { 26 27 if(index==S.size()) 28 29 { 30 31 32 33 for(int i=0;i<result.size();i++) 34 35 { 36 37 if(result[i]==tmp) 38 39 return; 40 41 } 42 43 result.push_back(tmp); 44 45 46 47 return; 48 49 } 50 51 52 53 getSubset(result,S,index+1,tmp); 54 55 tmp.push_back(S[index]); 56 57 getSubset(result,S,index+1,tmp); 58 59 } 60 61 };
考虑在寻找子集时,就去重,按照下面的方式进行。
假设1,2,3,3
初始时,什么都没选[]
当只有一个元素时:[1],[2],[3]重复的被去除
当有两个元素时:[12],[13],[23],[33]
当有三个元素时:[123],[133],[233]
可以按照如下的递归算法进行:
1 class Solution { 2 3 public: 4 5 vector<vector<int> > subsetsWithDup(vector<int> &S) { 6 7 8 9 vector<vector<int> > result; 10 11 vector<int> tmp; 12 13 sort(S.begin(),S.end()); 14 15 getSubset(result,S,0,tmp); 16 17 return result; 18 19 } 20 21 22 23 void getSubset(vector<vector<int> > &result,vector<int> &S,int index,vector<int> tmp) 24 25 { 26 27 result.push_back(tmp); 28 29 30 31 for(int i=index;i<S.size();i++) 32 33 { 34 35 if(i>index&&S[i]==S[i-1])continue; 36 37 38 39 tmp.push_back(S[i]); 40 41 getSubset(result,S,i+1,tmp); 42 43 tmp.pop_back(); 44 45 } 46 } 47 48 };
时间: 2024-10-12 13:09:38