我有一個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