Enumerate all k-partitions of 1d array with N elements?

前端 未结 2 695
借酒劲吻你
借酒劲吻你 2021-01-12 10:43

This seems like a simple request, but google is not my friend because \"partition\" scores a bunch of hits in database and filesystem space.

I need to enumerate all

相关标签:
2条回答
  • 2021-01-12 11:44

    In order to re-use the prior results (for lesser values of k), you can do recursion.

    Think of such partitioning as a list of ending indexes (starting index for any partition is just the ending index of the last partition or 0 for the first one).

    So, your set of partitionings are just a set of all arrays of k non-decreasing integers between 0 and N.

    If k is bounded, you can do this via k nested loops

    for (i[0]=0; i[0] < N; i[0]++) {
        for (i[1]=i[0]; i[1] < N; i[1]++) {
        ...
                for (i[10]=i[9]; i[10] < N; i[10]++) {
                    push i[0]==>i[10] onto the list of partitionings.
                }
        ...
        }
    }
    

    If k is unbounded, you can do it recursively.

    A set of k partitions between indexes S and E is obtained by:

    • Looping the "end of first partition" EFP between S and E. For each value:

      • Recursively find a list of k-1 partitions between EFP and S

      • For each vector in that list, pre-pend "EFP" to that vector.

      • resulting vector of length k is added to the list of results.

    Please note that my answer produces lists of end-points of each slice. If you (as your example shows) want a list of LENGTHS of each slice, you need to obtain lengths by subtracting the last slice end from current slice end.

    0 讨论(0)
  • Each partition can be described by the k-1 indexes separating the parts. Since order is preserved, these indices must be non-decreasing. That is, there is a direct correspondence between subsets of size k-1 and the partitions you seek.

    For iterating over all subsets of size k-1, you can check out the question:

    How to iteratively generate k elements subsets from a set of size n in java?

    The only wrinkle is that if empty parts are allowed, several cut-points can coincide, but a subset can contain each index at most once. You'll have to adjust the algorithm slightly by replacing:

            processLargerSubsets(set, subset, subsetSize + 1, j + 1);
    

    by

            processLargerSubsets(set, subset, subsetSize + 1, j);
    
    0 讨论(0)
提交回复
热议问题