问题开始之前, 首先介绍一下利用C++ 头文件<algorithm>中的next_permutation()和pre_permutation产生0, 1, 2, 3, ... N - 1全排列。 这两个函数
产生全排的办法是通过字典序的原理。 next_permutation() 按照递增的办法产生字典序的下一个(唯一确定的, 与当前的排列之间不能夹杂了任何可行的
排列)。 prev_permutation() 产生当前排列的字典序的上一个排列, 是按照递减的顺序。 即产生的字典序比当前排列小的。
下面利用next_permutation产生0, 1, ... N - 1 的所有的全排列的方法:
// next_permutation example
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort
int main () {
int myints[] = {1,2,3};
std::sort (myints,myints+3); // 必须有这一步, 否则可能产生不完全
std::cout << "The 3! possible permutations with 3 elements:\n";
do {
std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
} while ( std::next_permutation(myints,myints+3) );
std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
return 0;
}
运行结果如下:
当然也可以采用递归的办法产生, 方法如下:
#include <iostream>
using namespace std;
void swap(char *fir, char *sec)
{
char temp = *fir;
*fir = *sec;
*sec = temp;
}
/* arr is the string, curr is the current index to start permutation from and size is sizeof the arr */
void permutation(char *