【问题标题】:Algorithm for permutations of line subdivision线细分排列的算法
【发布时间】:2017-09-09 16:55:08
【问题描述】:

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

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

我们将不胜感激。

谢谢

【问题讨论】:

  • 您还想根据订单进行区分吗?例如,细分 |--|-|--||-|--|--| 应该单独列出还是只列出一次?
  • 您正在寻找的技术术语是“分区”。试试这个作为搜索关键字。
  • @Socowi 是的,订单很重要。谢谢

标签: algorithm permutation partitioning division segment


【解决方案1】:

您可以通过递归选择下一段的长度来做到这一点。

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多