我想要生成一个集合(一组)的所有排列,例如:
Collection: 1, 2, 3
Permutations: {1, 2, 3}
{1, 3, 2}
{2, 1, 3}
{2, 3, 1}
{3, 1, 2}
{3, 2, 1}
这不是一个普遍的“如何”问题,而是更多关于如何最有效地解决问题。此外,我不想生成所有排列并返回它们,而只是一次生成一个排列,并在必要时继续(就像迭代器一样 - 我也尝试过,但效率不高)。
我测试了许多算法和方法,并得出了这个代码,它是我尝试过的最有效的代码:
public static bool NextPermutation<T>(T[] elements) where T : IComparable<T>
{
// More efficient to have a variable instead of accessing a property
var count = elements.Length;
// Indicates whether this is the last lexicographic permutation
var done = true;
// Go through the array from last to first
for (var i = count - 1; i > 0; i--)
{
var curr = elements[i];
// Check if the current element is less than the one before it
if (curr.CompareTo(elements[i - 1]) < 0)
{
continue;
}
// An element bigger than the one before it has been found,
// so this isn't the last lexicographic permutation.
done = false;
// Save the previous (bigger) element in a variable for more efficiency.
var prev = elements[i - 1];
// Have a variable to hold the index of the element to swap
// with the previous element (the to-swap element would be
// the smallest element that comes after the previous element
// and is bigger than the previous element), initializing it
// as the current index of the current item (curr).
var currIndex = i;
// Go through the array from the element after the current one to last
for (var j = i + 1; j < count; j++)
{
// Save into variable for more efficiency
var tmp = elements[j];
// Check if tmp suits the "next swap" conditions:
// Smallest, but bigger than the "prev" element
if (tmp.CompareTo(curr) < 0 && tmp.CompareTo(prev) > 0)
{
curr = tmp;
currIndex = j;
}
}
// Swap the "prev" with the new "curr" (the swap-with element)
elements[currIndex] = prev;
elements[i - 1] = curr;
// Reverse the order of the tail, in order to reset it's lexicographic order
for (var j = count - 1; j > i; j--, i++)
{
var tmp = elements[j];
elements[j] = elements[i];
elements[i] = tmp;
}
// Break since we have got the next permutation
// The reason to have all the logic inside the loop is
// to prevent the need of an extra variable indicating "i" when
// the next needed swap is found (moving "i" outside the loop is a
// bad practice, and isn't very readable, so I preferred not doing
// that as well).
break;
}
// Return whether this has been the last lexicographic permutation.
return done;
}
它的用法是发送一个元素数组,返回一个布尔值,指示这是否是最后一个字典排序排列,同时将数组改变为下一个排列。
使用示例:
var arr = new[] {1, 2, 3};
PrintArray(arr);
while (!NextPermutation(arr))
{
PrintArray(arr);
}
事实上,我对代码的速度不满意。
遍历大小为11的数组的所有排列需要大约4秒钟。虽然这可以被认为是令人印象深刻的成就,因为大小为11的集合的可能排列数是近4000万个。
从逻辑上讲,对于大小为12的数组,它将需要大约12倍的时间,因为12!等于11!* 12,对于大小为13的数组,它将需要比大小为12的数组多大约13倍的时间,以此类推。
因此,您可以轻松理解,在大小为12及以上的数组中,浏览所有排列确实需要很长时间。
我有一种强烈的预感,我可以通过某种方式大大缩短时间(而不是切换到除C#之外的其他语言-因为编译器优化确实可以很好地进行优化,而且我怀疑我手动使用汇编语言无法进行如此良好的优化)。
有人知道任何其他更快的方法吗?您有任何想法可以使当前算法更快吗?
请注意,我不想使用外部库或服务来完成这项工作-我希望拥有代码本身,并且希望尽可能高效。