【问题标题】:Enumerate all possible distributions of n balls into k boxes [duplicate]将n个球的所有可能分布枚举到k个盒子中[重复]
【发布时间】:2017-11-17 22:18:24
【问题描述】:

我所指的确切问题和问题的分布数量是计算here。我有兴趣明确了解这些分布。

例如,有 5 个球和 3 个盒子:一种分布是盒子 1 中的 2 个球,盒子 2 中的 2 个,盒子 3 中的 1 个称为 221。现在我想列出所有这些可能的分布:-

212

131

104

。 . .

一种方法是我运行 matlab 命令:perms([0,0,0,0,0,1,1,1])。这基本上生成了 5 个球和 2 个棍子的所有排列。但是由于命令perms 无法识别相同的对象,因此存在大量过度计数。

【问题讨论】:

    标签: algorithm matlab combinations permutation combinatorics


    【解决方案1】:

    非常简单......有点。

    function alloc(balls, boxes):
    
        if boxes = 1
            return [balls]
        else
           for n in range 0:balls
               return alloc(balls-n, boxes-1)
    

    这就是基本的递归逻辑:挑选每个可能数量的球,然后在剩余的球上递归并减少一个盒子。

    列表粘合方法将取决于语言;我把它们留给学生练习。

    【讨论】:

      【解决方案2】:

      您可以使用unique() 删除由perms() 生成的相同行:

      A = unique(perms([0,0,0,0,0,1,1,1]), 'rows');
      % `A` will contain all combinations, not permutations, of [0,0,0,0,0,1,1,1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-09
        • 1970-01-01
        相关资源
        最近更新 更多