zoukankan      html  css  js  c++  java
  • 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 };
     
  • 相关阅读:
    poj2431 Expedition 题解报告
    poj1017 Packets 题解报告
    UVA714 Copying books 题解报告
    poj3040 Allowance 题解报告
    CH134 双端队列 题解报告
    poj2259 Team Queue 题解报告
    CH128 Editor 题解报告
    基本数据结构专题笔记
    CH109 Genius ACM 题解报告
    线段树总结
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5154486.html
Copyright © 2011-2022 走看看