线细分排列算法

时间:2017-04-13 14:06:00

标签: algorithm permutation division segment

我正在尝试找到一个代码/算法,以获得细分线或线段的所有可能的排列。在这里,假设你有一个5英寸的线,你可以将它分成5个块,每个1英寸,或2 x 2英寸的段+ 1段1英寸......等等...

是否有算法可以找到给定段的所有可能的细分排列?

对此的任何帮助都是合理的。

谢谢

1 个答案:

答案 0 :(得分:0)

您可以通过递归选择下一段的长度来完成此操作。

def find_partitions(length_remaining,only_decreasing_lengths=True,A=None):
    longest = length_remaining
    if A is None:
        A = []
    elif only_decreasing_lengths:
        longest = min(longest,A[-1])
    if longest==0:
        print A
    for x in range(1,longest+1):
        find_partitions(length_remaining-x,only_decreasing_lengths,A+[x])

print 'Decreasing'
find_partitions(5)
print 'Any order'
find_partitions(5,False)

如果订单很重要,则不清楚,因此此代码支持这两种方法。

打印出来:

Decreasing
[1, 1, 1, 1, 1]
[2, 1, 1, 1]
[2, 2, 1]
[3, 1, 1]
[3, 2]
[4, 1]
[5]
Any order
[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 2, 1]
[1, 1, 3]
[1, 2, 1, 1]
[1, 2, 2]
[1, 3, 1]
[1, 4]
[2, 1, 1, 1]
[2, 1, 2]
[2, 2, 1]
[2, 3]
[3, 1, 1]
[3, 2]
[4, 1]
[5]