You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.

If we use a matching pair of parentheses to represent a bag, the ways are:

For 1 bag, there's one way:

 ()	<- a bag

for 2 bags, there's one way:

 (())	<- one bag in another

for 3 bags, there are two:

 ((())) <- 3 bags nested Russian doll style
 (()()) <- 2 bags side by side, inside the third

for 4 bags, four:

 (()()())
 ((())())
 ((()()))
 (((())))

Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.

It's easy to see that each configuration for n bags represents a n-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given n is given by OEIS A81.



Task
 
Write a program that, when given n, enumerates all ways of nesting n bags.   You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.

This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.

As an example output, run 5 bags.   There should be 9 ways.




import std.stdio, std.conv;
 
alias Tree = ulong,
      TreeList = Tree[],
      Offset = uint[32];
 
void listTees(in uint n, in ref Offset offset, in TreeList list) nothrow @nogc @safe {
    static void show(in Tree t, in uint len) nothrow @nogc @safe {
        foreach (immutable i; 0 .. len)
            putchar(t & (2 ^^ i) ? '(' : ')');
    }
 
    foreach (immutable i; offset[n] .. offset[n + 1]) {
        show(list[i], n * 2);
        putchar('\n');
    }
}
 
void append(in Tree t, ref TreeList list, ref uint len) pure nothrow @safe {
    if (len == list.length)
        list.length = list.length ? list.length * 2 : 2;
    list[len] = 1 | (t << 1);
    len++;
}
 
/**
Assemble tree from subtrees.
 
Params:
  n   = length of tree we want to make.
  t   = assembled parts so far.
  sl  = length of subtree we are looking at.
  pos = offset of subtree we are looking at.
  rem = remaining length to be put together.
*/
void assemble(in uint n, in Tree t, uint sl, uint pos, in uint rem, in ref Offset offset,
              ref TreeList list, ref uint len) pure nothrow @safe {
    if (!rem) {
        append(t, list, len);
        return;
    }
 
    if (sl > rem) { // Need smaller subtrees.
        sl = rem;
        pos = offset[sl];
    } else if (pos >= offset[sl + 1]) {
        // Used up sl-trees, try smaller ones.
        sl--;
        if (!sl)
            return;
        pos = offset[sl];
    }
 
    assemble(n, t << (2 * sl) | list[pos], sl, pos, rem - sl, offset, list, len);
    assemble(n, t, sl, pos + 1, rem, offset, list, len);
}
 
void makeTrees(in uint n, ref Offset offset,
               ref TreeList list, ref uint len) pure nothrow @safe {
    if (offset[n + 1])
        return;
    if (n)
        makeTrees(n - 1, offset, list, len);
 
    assemble(n, 0, n - 1, offset[n - 1], n - 1, offset, list, len);
    offset[n + 1] = len;
}
 
void main(in string[] args) {
    immutable uint n = (args.length == 2) ? args[1].to!uint : 5;
    if (n >= 25)
        return;
 
    Offset offset;
    offset[1] = 1;
 
    Tree[] list;
    uint len = 0;
 
    // Init 1-tree.
    append(0, list, len);
 
    makeTrees(n, offset, list, len);
    stderr.writefln("Number of %d-trees: %u", n, offset[n + 1] - offset[n]);
    listTees(n, offset, list);
}