Leetcode 90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

 1 class Solution {
 2 public:
 3     vector<vector<int>> subsetsWithDup(vector<int>& nums) {
 4         sort(nums.begin(),nums.end());
 5         //无重复
 6         int tag = 0;
 7         int record = 0;
 8         vector<vector<int>> result;
 9         vector<int> line;
10         result.push_back(line);
11         line.push_back(nums[0]);
12         result.push_back(line);
13         for(int i = 1;i<nums.size();i++){
14             if(nums[i]!=nums[i-1]){
15                 int n = result.size();
16                 for(int j = 0; j<n ; j++){
17                      vector<int> temp = result[j];
18                      temp.push_back(nums[i]);
19                      result.push_back(temp);
20                      tag = 0;
21                 }
22                 record = n;
23             }
24             if(nums[i]==nums[i-1]){
25                 int n = result.size();
26                 if(tag == 0){//上一个没有重复
27                     for(int j = n/2;j<n;j++){
28                      vector<int> temp = result[j];
29                      temp.push_back(nums[i]);
30                      result.push_back(temp);
31                      tag = 1;
32                     }
33                     record = n/2;
34                 }
35                 else if(tag == 1){
36                     for(int j = n-record;j<n;j++){
37                         vector<int> temp = result[j];
38                         temp.push_back(nums[i]);
39                         result.push_back(temp);
40                         tag = 1;
41                     }
42                     record = record;
43                 }
44                 
45             }
46         }
47         return result;
48     }
49 };

 

posted on 2016-06-06 16:07  时间的女儿  阅读(174)  评论(0编辑  收藏  举报

导航