排列-所有可能的数字集 [英] Permutations - all possible sets of numbers
问题描述
我有一个从0到8的数字.我希望得到这些数字的所有可能的集合,每个集合都应使用所有数字,每个数字在一个集合中只能出现一次.
I have numbers, from 0 to 8. I would like in result, all possible sets of those numbers, each set should use all numbers, each number can occur only once in a set.
我希望看到用PHP制作的解决方案可以打印出结果.或者,至少,我希望在组合理论上有所收获,因为我早已忘记了这一点.计算多少个排列的公式是什么?
I would like to see solution made in PHP that could print out result. Or, at least, I would like some refreshment in theory of combinatorics, as I have long forgotten it. What is the formula to calculate how many permutations will there be?
示例集:
- 0-1-2-3-4-5-6-7-8
- 0-1-2-3-4-5-6-8-7
- 0-1-2-3-4-5-8-6-7
- 0-1-2-3-4-8-5-6-7
- 0-1-2-3-8-4-5-6-7
- 0-1-2-8-3-4-5-6-7
- 依此类推...
推荐答案
您正在寻找置换公式:
nPk = n!/(n-k)!
在您的情况下,您有9个条目,并且想要选择所有条目,那就是9P9 = 9! = 362880
In your case, you have 9 entries and you want to choose all of them, that's 9P9 = 9! = 362880
您可以在O'Reilly的"PHP Cookbook"的食谱4.26中找到一种可置换的PHP算法.
You can find a PHP algorithm to permutate in recipe 4.26 of O'Reilly's "PHP Cookbook".
pc_permute(array(0, 1, 2, 3, 4, 5, 7, 8));
从O'Reilly复制:
Copied in from O'Reilly:
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);
}
}
}
这篇关于排列-所有可能的数字集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!