【问题标题】:How to calculate the max. number of combinations possible? [duplicate]如何计算最大值。可能的组合数量? [复制]
【发布时间】:2010-08-06 17:00:04
【问题描述】:

可能的重复:
Display possible combinations of string
algorithm that will take numbers or words and find all possible combinations

如果我有 3 个字符串,例如:

"abc def xyz"

我想通过重新排列这些字符串来找到我可以生成的最大组合数,例如:

  • abc xyz def
  • def xyz abc
  • xyz abc def

等等。计算这个的公式/算法是什么?

【问题讨论】:

  • Display possible combinations of stringa couple others 的可能重复项,例如 stackoverflow.com/questions/1256117/… - 我记得还有一些,但现在懒得找了。
  • 字符串可以重复吗?像“abc abc def”?
  • @Gordon 这不是那个的副本。他只是在询问排列的数量。
  • @Artefacto。如果 OP 只要求总数的公式,那么它就是题外话!无论哪种情况,这个问题都应该结束。
  • @Moron 这并不是真正的题外话,因为他问他如何用特定的编程语言 (PHP) 计算数字,即如何实现给出该数字的算法。询问f: x->xab 之间的积分是多少和要求一种算法来确定所述积分是不同的。

标签: php algorithm powerset


【解决方案1】:

这不是组合,而是排列。该算法是 n! 其中 n 是元素的数量。

为什么?

因为您有 3 个值要放置在三个位置,所以第一个位置您有三个选项,第二个只有两个(因为您已经在第一个字符串中放置),最后您只有一个选项。

3 * 2 * 1 = 3! = 6

但是如果你可以重复这些选择,那么你就有了重复排列

所以第一名你可以从3个字符串中选择,第二个也可以选择一个

3 * 3 * 3 = 3^3 = 27

n^k - 其中 n 是字符串的数量,k - “位置”的数量

而代码算法是这样的:

function fact($n)
{
  if ($n == 0)
  {
    return 1;
  }
  else
  {
    return $n * fact($n - 1);
  }
}

这是一个递归示例

【讨论】:

  • 这个问题没有说任何关于独特性的内容,所以不确定你是否可以假设它。当然,OP 似乎忽略了这方面的询问,所以...
【解决方案2】:

如果我没记错的话是 n!组合。

所以你会得到 9 个

9*8*7*6*5*4*3*2 = 362880 种组合

【讨论】:

  • n!是“排列”,而不是“组合”
【解决方案3】:

研究排列。 O'Reilley 通过 google 提供了一些很好的信息。如果我有一些额外的时间,我会试着为你起草一个例子。

更新

这里有一些代码,如果它工作正常,不是 100%,但你应该能够根据需要对其进行修改(核心代码来自 O'Reilley 网站,仅供参考):

<?php
function pc_permute($items, $perms = array( )) {
    if (empty($items)) { 
        print join(' ', $perms) . "\n";
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}

pc_permute(array('abc', 'xyz', 'def', 'hij'));
?>

编辑

刚刚看到他想要该算法,或者代码应该为其他潜伏者产生结果:) 查看算法的其他答案,即 n!

【讨论】:

    【解决方案4】:

    3*2*1= 6 阶乘!

    3 个字符串 = 6 个组合..... 4 个字符串 = 24 个组合......等等

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-23
      • 2013-01-17
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多