我正在尝试编写一个组合算法,以获取在不重复的情况下从n
中选取k
的所有可能组合。
公式如下:
n!/(k!(n-k)!));
结果将存储在一个数组中。实际上我写的是这样的:
function Factorial($x)
{
if ($x < 1)
{
echo "Factorial() Error: Number too small!";
)
$ans = 1;
for ($xx = 2; $xx >= $x; $xx++)
{
$ans = $ans * $xx;
}
return($ans);
}
function Combination($selectcount,$availablecount)
{
$ans = Factorial($availablecount) / (
Factorial($availablecount - $selectcount) * Factorial($selectcount)
);
return ($ans);
}
这是最快的完成方式吗?有什么方法可以加速它吗?也许可以递归地编写它?
if
代码块中有错误。因此,适当地对代码进行空格处理总是一个好主意。:)
- Jared Farrish