代码改变世界

[LeetCode]Subsets II

2014-03-24 19:49  庸男勿扰  阅读(237)  评论(0编辑  收藏  举报

原题链接:http://oj.leetcode.com/problems/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],
  []
]

题解:

  这题是含重复元素的子集生成,简化版本是集合中无重复元素,见http://www.cnblogs.com/codershell/p/3619928.html,

  我在《子集问题(寻找给定集合的所有子集)》一文中详细分析了子集问题,具体解释不再赘述。

 1 class Solution {
 2 public:
 3     bool isExist(vector<vector<int> > &vv,vector<int> v){
 4         for(int i=0; i<vv.size(); i++)
 5             if(vv[i] == v)
 6                 return true;
 7                 
 8         return false;
 9     }
10     
11     void ss(vector<vector<int> > &vv,int* flag,int n, vector<int> &S, int cur){
12         if(cur == n){
13             vector<int> v;
14             for(int i = 0; i < cur; i++)
15                 if(flag[i])
16                     v.push_back(S[i]);
17             if(!isExist(vv,v))
18                 vv.push_back(v);
19             return;
20         }
21         
22         flag[cur] = 1;                                // 选第 cur 个元素
23         ss(vv,flag,n, S, cur+1);
24         flag[cur] = 0;                                // 不选第 cur 个元素
25         ss(vv,flag,n, S, cur+1);
26     }
27     
28     vector<vector<int> > subsetsWithDup(vector<int> &S) {
29         int *flag = (int *)malloc(sizeof(int) * S.size()) ;
30         
31         vector <vector<int>> array;
32         sort(S.begin(),S.end());
33         ss(array,flag,S.size(),S,0);
34         free(flag);
35         return array;
36     }
37 };
View Code