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

前端 未结 2 712
借酒劲吻你
借酒劲吻你 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

    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);
    

提交回复
热议问题