• [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 };
  • 相关阅读:
    320 Generalized Abbreviation
    319. Bulb Switcher
    三条用人原则
    Go 编码问题的解决方案
    C# MVC js 跨域
    apidoc接口文档的快速生成
    go语言学习
    C#系统之垃圾回收
    WCF项目启动时错误处理
    XML之XPath
  • 原文地址:https://www.cnblogs.com/chkkch/p/2772209.html
Copyright © 2020-2023  润新知