我有一个N项列表,我想知道如何通过列表循环来获取每个组合。没有双打,所以我需要得到所有N!排序。额外的内存是没有问题的,我试图想到最简单的算法,但我遇到了麻烦。N ++的C++算法!排序
回答
C++ STL具有next_permutation用于此目的。
扩大别人的答案,这里是性病的例子::使用递归从cplusplus.com
#include <iostream>
#include <algorithm>
using namespace std;
void outputArray(int* array, int size)
{
for (int i = 0; i < size; ++i) { cout << array[i] << " "; }
}
int main()
{
int myints[] = { 1, 2, 3, 4, 5 };
const int size = sizeof(myints);
cout << "The 5! possible permutations with 5 elements:\n";
sort (myints, myints + size);
bool hasMorePermutations = true;
do
{
outputArray(myints, size);
hasMorePermutations = next_permutation(myints, myints + size);
}
while (hasMorePermutations);
return 0;
}
+1提供了一个例子。 – 2010-01-26 19:59:28
'bool'变量中似乎没有任何一点。你可以'做{...} while(std :: next_permutation(...));' – 2010-01-26 22:03:20
@Charles:这是真的,我可以做到这一点。出于教学目的,我从中取出next_permutation,因为这是代码的重点。 – Bill 2010-01-26 22:18:54
简单的算法调整next_permutation:
伪
getPermutations(CurItemList , CurPermList)
if CurItemList.isempty()
return CurPermList
else
Permutations = {}
for i = 1 to CurItemList.size()
CurPermList.addLast(CurItemList.get(i))
NextItemList = CurItemList.copy()
NextItemList.remove(i)
Permutations.add(getPermutations(NextItemList, CurPermList))
CurPermList.removeLast()
return Permutations
// To make it look better
Permutations(ItemList)
return getPermutations(ItemList, {})
我没有测试它,但应该工作。也许它不是最聪明的做法,但它是一个简单的方法。 如果有什么不对,请让我知道!
尝试使用固定数量的可能元素递归地构建一组组合。所有可能组合的集合将是1个元素,2个元素,...到N个元素的组合的集合。
然后你可以单独攻击每个固定大小的组合。
- 1. O(n)排序算法可能吗?
- 2. 部分排序为N个未排序组的有效算法
- 3. 通用实用的排序算法比O(n log n)快吗?
- 4. C中排序算法的错误(基数排序的变异)
- 5. N-gram的C#算法
- 6. 排序d排序数组的算法
- 7. 排序列表的对象,使用排序()算法c + +
- 8. 排序算法2
- 9. 使用Qt/C++排序算法 - 排序结构的QList结构
- 10. 按字母顺序排序使用插入排序算法c#
- 11. 如何改进已经是O(n)的递归排序算法?
- 12. 对N个数据流进行时间排序的算法
- 13. 排序算法整数最多有n个点的整数
- 14. 与快速排序算法混淆C#
- 15. 排序变长项/算法
- 16. 算法 - 计算O(n)中排序数组中所有对数相等的数?
- 17. 排序算法的效率
- 18. 排序算法的Java
- 19. 为什么我的气泡排序算法比我的程序中选择和插入排序算法更快?
- 20. Javascript排序算法,jQuery的也许
- 21. 排序算法的时间复杂度
- 22. 排序/交换结构的矢量的要素快速排序算法(C++)
- 23. 算法在未排序的阵列
- 24. 排序算法的复杂性
- 25. 的JavaScript的算法“排序()”函数
- 26. 排序算法 - 使用Javascript
- 27. 排序算法太慢ArrayList
- 28. 排序算法问题
- 29. 合并排序Java算法
- 30. 选择排序算法Python
它是组合还是置换? – sud03r 2010-01-26 19:19:05
另请参阅http://stackoverflow.com/questions/352203/generating-permutations-lazily/ – ShreevatsaR 2010-07-13 13:08:53