zoukankan      html  css  js  c++  java
  • [Leetcode 105] 90 Subsets II

    Problem:

    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],
      []
    ]

    Analysis:

    This is a viration of basic DFS. The given int vector contains duplicated elements. To avoid dup-enumeration, we need first sort the given vector so that the enumeration is ordered. Then we need an extra signal array to indicate whether an element is accessed. We pick an element only if 1) it's different from the previous element or 2) it's the same as the previous one but the previous element has already be selected. In this way, we can ensure no duplicated subsets are generated.

    Code:

     1 class Solution {
     2 public:
     3     vector<vector<int> > res;
     4     vector<int> tmp;
     5     int *sig;
     6     int size;
     7 
     8     vector<vector<int> > subsetsWithDup(vector<int> &S) {
     9         // Start typing your C/C++ solution below
    10         // DO NOT write int main() function
    11         res.clear();
    12         tmp.clear();
    13         
    14         size = S.size();
    15         sig = new int[size];
    16         for (int i=0; i<size; i++)
    17             sig[i] = 0;
    18 
    19         std::sort(S.begin(), S.end());
    20         solve(0, S);
    21         
    22         return res;
    23     }
    24     
    25 private:
    26     bool solve(int n, vector<int> &S) {
    27         res.push_back(tmp);
    28 
    29         if (n == size) return true;
    30 
    31         for (int i=n; i<size; i++) {
    32             if ((i==0) || (S[i-1] != S[i]) || (S[i-1] == S[i] && sig[i-1])) {
    33                 sig[i] = 1;
    34                 tmp.push_back(S[i]);
    35                 
    36                 solve(i+1, S);
    37                 
    38                 tmp.pop_back();
    39                 sig[i] = 0;
    40             }
    41         }
    42         
    43         return false;
    44     }
    45 };
    View Code
  • 相关阅读:
    周记 2016.3.29
    Java ActiveMQ 讲解(一)理解JMS 和 ActiveMQ基本使用(转)
    聊聊架构01
    乐观锁和悲观所
    数据库锁(转)
    ActiveMQ消息的可靠性机制(转)
    DOM
    JavaScript
    CSS之background
    CSS之overflow
  • 原文地址:https://www.cnblogs.com/freeneng/p/3251281.html
Copyright © 2011-2022 走看看