zoukankan      html  css  js  c++  java
  • [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],
      []
    ]

    用一个数组来记录某个数字是否被使用过,如果前面的数字和本数相同,则前面的数必须被使用过本数才能被使用。
     1 class Solution {
     2 private:
     3     vector<vector<int> > ret;
     4     bool canUse[100];
     5 public:
     6     void dfs(int dep, int maxDep, vector<int> &num, vector<int> a, int start)
     7     {
     8         ret.push_back(a);
     9         
    10         if (dep == maxDep)
    11             return;
    12             
    13         for(int i = start; i < num.size(); i++)
    14             if (i == 0)
    15             {
    16                 canUse[i] = false;
    17                 vector<int> b(a);
    18                 b.push_back(num[i]);
    19                 dfs(dep + 1, maxDep, num, b, i + 1);
    20                 canUse[i] = true; 
    21             }
    22             else
    23             {
    24                 if (num[i] == num[i-1] && canUse[i-1])
    25                     continue;
    26                     
    27                 canUse[i] = false;
    28                 vector<int> b(a);
    29                 b.push_back(num[i]);
    30                 dfs(dep + 1, maxDep, num, b, i + 1);
    31                 canUse[i] = true;
    32             }          
    33     }
    34     
    35     vector<vector<int> > subsetsWithDup(vector<int> &S) {
    36         // Start typing your C/C++ solution below
    37         // DO NOT write int main() function
    38         sort(S.begin(), S.end());
    39         ret.clear();
    40         memset(canUse, true, sizeof(canUse));
    41         vector<int> a;
    42         dfs(0, S.size(), S, a, 0);
    43         return ret;
    44     }
    45 };
  • 相关阅读:
    MO 中的imagelayer
    GDAL之OGR入门(转载)
    OGR体系结构
    C++与C# 以及指针
    如何用C#编程实现动态生成Word文档并填充数据?
    C++的类与C#的类[zt]
    arcmap vba 实现“卫星立体测图”高度字段值的计算,今天的一点小成就
    lib 和 dll from baidu
    ping and netstat
    Visual Basic6.0 中的类模块和标准模块
  • 原文地址:https://www.cnblogs.com/chkkch/p/2772209.html
Copyright © 2011-2022 走看看