• Subsets II -- LeetCode


    Given a collection of integers that might contain duplicates, nums, 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 nums = [1,2,2], a solution is:

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

    思路:我们先考虑所有数字不重复出现的情况。那么所有子集的个数是2^n,即每个数字都只有出现或者不出现这2种情况。而当数字重复出现时,我们将该数字视为一种特殊的数字。比如说输入中含有2个5,那么我们就有3种选择:不选5,选1个5,选2个5。
     1 class Solution {
     2 public:
     3     void help(vector<vector<int> >& res, vector<int>& nums, vector<int> cand, int cur)
     4     {
     5         if (cur == nums.size())
     6         {
     7             res.push_back(cand);
     8             return;
     9         }
    10         int nex, n = nums.size();
    11         for (nex = cur + 1; nex < n && nums[nex] == nums[cur]; nex++);
    12         help(res, nums, cand, nex);
    13         for (int i = cur; i < nex; i++)
    14         {
    15             cand.push_back(nums[i]);
    16             help(res, nums, cand, nex);
    17         }
    18     }
    19     vector<vector<int>> subsetsWithDup(vector<int>& nums) {
    20         sort(nums.begin(), nums.end(), less<int>());
    21         vector<int> cand;
    22         vector<vector<int> > res;
    23         help(res, nums, cand, 0);
    24         return res;
    25     }
    26 };
     
  • 相关阅读:
    setTimeOut与循环闭包问题
    ES6----class用法
    JS------对象的继承方式
    JavaScript对象 -构建
    nodejs异步---Async
    mongdb位置索引
    mongodb 索引3
    mongod 索引2
    mongodb 索引1
    3 C++数据类型
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5154486.html
Copyright © 2020-2023  润新知