Algorithm to generate all multiset size-n partitions

后端 未结 3 1171
抹茶落季
抹茶落季 2021-02-09 18:42

I\'ve been trying to figure out a way to generate all distinct size-n partitions of a multiset, but so far have come up empty handed. First let me show what I\'m trying to archi

3条回答
  •  半阙折子戏
    2021-02-09 19:25

    Here's my pencil and paper algorithm:

    Describe the multiset in item quantities, e.g., {(1,2),(2,2)}
    
    f(multiset,result):
      if the multiset is empty:
        return result
      otherwise:
        call f again with each unique distribution of one element added to result and 
        removed from the multiset state
    
    
    Example:
    {(1,2),(2,2),(3,2)} n = 2
    
    11       -> 11 22    -> 11 22 33
                11 2  2  -> 11 23 23
    1  1     -> 12 12    -> 12 12 33
                12 1  2  -> 12 13 23
    
    
    Example:
    {(1,2),(2,2),(3,2)} n = 3
    
    11      -> 112 2   -> 112 233
               11  22  -> 113 223
    1   1   -> 122 1   -> 122 133
               12  12  -> 123 123
    

    Let's solve the problem commented below by m69 of dealing with potential duplicate distribution:

    {A,B,B,C,C,D,D,D,D}
    
    We've reached {A, , }{B, , }{B, , }, have 2 C's to distribute
    and we'd like to avoid `ac  bc  b` generated along with `ac  b   bc`.
    
    Because our generation in the level just above is ordered, the series of identical 
    counts will be continuous. When a series of identical counts is encountered, make 
    the assignment for the whole block of identical counts (rather than each one), 
    and partition that contribution in descending parts; for example,
    
          | identical |
    ac     b      b
    ac     bc     b     // descending parts [1,0]
    
    Example of longer block:
    
          |    identical block     |  descending parts
    ac     bcccc  b      b      b    // [4,0,0,0] 
    ac     bccc   bc     b      b    // [3,1,0,0]
    ac     bcc    bcc    b      b    // [2,2,0,0]
    ...
    

提交回复
热议问题