Stu*_*art 5 c++ permutation factorial
我有一个N项目列表,我想知道如何循环列表以获得每个组合.没有双打,所以我需要得到全部N!排序.额外的内存没有问题,我正在考虑最简单的算法,但我遇到了麻烦.
扩展其他人的答案,这是从cplusplus.com改编的std :: next_permutation的一个例子
#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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1566 次 |
| 最近记录: |