zoukankan      html  css  js  c++  java
  • [LeetCode]Subsets II

    原题链接:http://oj.leetcode.com/problems/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],
      []
    ]

    题解:

      这题是含重复元素的子集生成,简化版本是集合中无重复元素,见http://www.cnblogs.com/codershell/p/3619928.html,

      我在《子集问题(寻找给定集合的所有子集)》一文中详细分析了子集问题,具体解释不再赘述。

     1 class Solution {
     2 public:
     3     bool isExist(vector<vector<int> > &vv,vector<int> v){
     4         for(int i=0; i<vv.size(); i++)
     5             if(vv[i] == v)
     6                 return true;
     7                 
     8         return false;
     9     }
    10     
    11     void ss(vector<vector<int> > &vv,int* flag,int n, vector<int> &S, int cur){
    12         if(cur == n){
    13             vector<int> v;
    14             for(int i = 0; i < cur; i++)
    15                 if(flag[i])
    16                     v.push_back(S[i]);
    17             if(!isExist(vv,v))
    18                 vv.push_back(v);
    19             return;
    20         }
    21         
    22         flag[cur] = 1;                                // 选第 cur 个元素
    23         ss(vv,flag,n, S, cur+1);
    24         flag[cur] = 0;                                // 不选第 cur 个元素
    25         ss(vv,flag,n, S, cur+1);
    26     }
    27     
    28     vector<vector<int> > subsetsWithDup(vector<int> &S) {
    29         int *flag = (int *)malloc(sizeof(int) * S.size()) ;
    30         
    31         vector <vector<int>> array;
    32         sort(S.begin(),S.end());
    33         ss(array,flag,S.size(),S,0);
    34         free(flag);
    35         return array;
    36     }
    37 };
    View Code
  • 相关阅读:
    1052 Linked List Sorting (25 分)
    1051 Pop Sequence (25 分)
    1050 String Subtraction (20 分)
    1049 Counting Ones (30 分)
    1048 Find Coins (25 分)
    1047 Student List for Course (25 分)
    1046 Shortest Distance (20 分)
    1045 Favorite Color Stripe (30 分)
    1044 Shopping in Mars (25 分)
    1055 The World's Richest (25 分)
  • 原文地址:https://www.cnblogs.com/codershell/p/3621687.html
Copyright © 2011-2022 走看看