高效生成集合排列
在生成集合排列的问题中,找到最有效的算法至关重要。提供的代码实现了高效率,但对于要求较高的计算,寻求优化。
建议的解决方案:Knuth 算法
Knuth 算法提供了一种高效的排列生成方法。它的操作主要有四个步骤:
实现
提供的实现 Knuth 算法的 C# 代码如下:
private static bool NextPermutation(int[] numList) { // 1. Find the largest index j such that a[j] < a[j + 1]. If no such index exists, the permutation is the last permutation. var largestIndex = -1; for (var i = numList.Length - 2; i >= 0; i--) { if (numList[i] < numList[i + 1]) { largestIndex = i; break; } } // If no such index exists, return false indicating the last permutation. if (largestIndex < 0) return false; // 2. Find the largest index l such that a[j] < a[l]. Since j + 1 is such an index, l is well defined and satisfies j < l. var largestIndex2 = -1; for (var i = numList.Length - 1; i >= 0; i--) { if (numList[largestIndex] < numList[i]) { largestIndex2 = i; break; } } // 3. Swap a[j] with a[l]. var tmp = numList[largestIndex]; numList[largestIndex] = numList[largestIndex2]; numList[largestIndex2] = tmp; // 4. Reverse the sequence from a[j + 1] up to and including the final element a[n]. for (int i = largestIndex + 1, j = numList.Length - 1; i < j; i++, j--) { tmp = numList[i]; numList[i] = numList[j]; numList[j] = tmp; } return true; }
速度优化注意事项
为了进一步优化速度,请考虑以下:
以上是Knuth 算法如何高效生成集合排列?的详细内容。更多信息请关注PHP中文网其他相关文章!