这个函数是按照字典序用来生成全排列,做一些枚举,搜索啊这些很暴力的时候很有用,特别是需要字典序输出的时候,以前很苦恼的字典序问题用现在的方法,好像可以解决了。。
先来看一个例子:
#include <algorithm>
#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
int a[] = {1,2,3,5,6};
do {
for(int i = 0 ; i<5;i++)
printf("%d ",a[i]);
printf("\n");
} while(next_permutation(a,a+5));
}
这样就得到了从1到5的全排列,也就是
1 2 3 4 5
1 2 3 5 4
1 2 4 3 5
1 2 4 5 3
……
5 4 3 2 1
总共120个序列。
接下来是在next_permutation函数中使用字符串来写全序列:
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s = "abcde";
sort(s.begin(), s.end());
do {
cout << s << '\n';
} while(next_permutation(s.begin(), s.end()));
}
输出结果为:
abcde
abced
abdce
abdec
abecd
…..
edcba
至于它的用法。。下次找个题目来做一下,熟悉一下好了~