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,只不过多了一个判断条件,subset是否重复
 1 class Solution {
 2 public:
 3     vector<vector<int> >result;
 4     vector<int> s;
 5     int n;
 6 
 7     void dfs(vector<int> temp,int num){
 8         if( num == n){
 9             if(find(result.begin(),result.end(),temp) == result.end())
10                 result.push_back(temp);
11             return;
12         }
13 
14         dfs(temp,num+1);
15 
16         temp.push_back(s[num]);
17         dfs(temp,num+1);
18 
19     }
20     vector<vector<int> > subsetsWithDup(vector<int> &S) {
21         sort(S.begin(),S.end());
22 
23         result.clear();
24         vector<int> temp;
25 
26         s = S;
27         n = S.size();
28         dfs(temp,0);
29 
30         return result;
31     }
32 };

 



posted @ 2013-04-29 14:31  caijinlong  阅读(164)  评论(0编辑  收藏  举报