There is an important observation (in the commentary) that splitting a set of elements n can be represented as an integer sequence of the form [p 1 , & hellip; p n ], where p i is the section number of the element i. For such a sequence to be valid, it must obey the rules that p 1 is 1, and for each j, where 1 <j & le; n, there exists some i <j such that p j & le; p <sub> yasub> & plus; 1. Or, in other words, in any sequence prefix, no integer is skipped.
Now there is a standard algorithm for listing limited sequences in lexicographic order, which consists of the following:
- Start with the least sequence.
- To find the following sequence in lexicographical order:
- Scan back through the sequence and find the rightmost "incremental" element. (An incremental element is an element such that there is some larger element that can be replaced for this element, and the resulting subsequence to this point is a prefix of at least one valid sequence.)
- Change this item to the next larger item, which is viable (i.e. which results in a valid prefix as above), and then fill in the remaining items on the right (if any) with the smallest possible values.
- If there is no incremental element, then the enumeration is completed.
With several provisions for finding an incremental element, this algorithm is O (n) in the worst case, and often O (1), when the element to be enlarged is usually near the end of the sequence. (For example, using this algorithm to enumerate permutations is O (1) to find the next permutation if you can find the โnext elementโ in O (1).)
To apply this algorithm to the case of a section, we note the following:
- The smallest possible sequence is [1, & hellip; one]
- An element p i is incremental if:
- p <sub> Isub> <p
- There is some j <i such that p i & is equal to; p j
- The smallest suffix of a viable prefix is โโ[1, & hellip; one]
Another way to state the condition in observation 2 is that an element is incremental if its value is n or it is the first element in the sequence with its value. We can make this definition in O (1) if we also keep the sequence [m 1 , & hellip; m n ], where m 1 is 0, and m i is the maximum m i-1 and p <sub> I-1sub>. m is trivial to support, and this allows us to rewrite the increment condition as simply p i & le; m i .
It is easy to see that Next Partition can be implemented in O (n) time, but, as it happens, it also takes place that this is the depreciation time of O (1). Roughly speaking, this is because in most cases the last element of the sequence is incremental.
rici
source share