#include <iostream>
#define MAX_M 10
#define MAX_N 10
using namespace std;
bool used[MAX_N];
int perm[MAX_M];
// 生成{1,2,3,4,....,n-1}的n!种排列
void permutation1(int pos,int n){
if (pos == n){
cout << n << ' ';
return ;
}
// 针对perm的第pos个位置,究竟使用0~n-1中的哪个循环
for (int i = 0;i < n;i ++){
if (!used[i]){
perm[pos] = i;
// i已经被使用过了,所以把标志设置为true
used[i] = true;
permutation1(pos + 1,n);
// 返回之后把标志复位
used[i] = false;
}
}
return ;
}
#include <algorithm>
// 即使有重复元素也会生成所有的排列
// next_permutation是按照字典序来生成下一个排列的
int perm2[MAX_N];
void permutation2(int n){
for (int i = 0;i < n;i ++)
perm2[i] = i;
do {
cout << n << ' ';
} while (next_permutation(perm2,perm2 + n));
// 所以排列都生成后,next_permutation会返回false
return ;
}
int main()
{
permutation1(7,10); // 生成 10!/7!
permutation2(8); // 生成8!
}
上面的代码可能有点难懂,那么我们现在就看一下新型的代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
struct Rule{
bool operator()(char & a,char & b){
return a > b;
}
};
int main()
{
char ch[205];
cin >> ch;
sort(ch,ch+strlen(ch),Rule());
char *first = ch;
char *last = ch + strlen(ch);
do{
cout << ch << endl;
}while (next_permutation(ch,ch+3,Rule()));
}
其中上面的表达式,next_permutation 可以用地址,或者是迭代器(指针)来实现,并且,可以自定义实现的结果。