C++  全排列函数。。。一听名字就在<algorithm>中。。。

首先第一个说的是next_permutation:

#include <algorithm> bool next_permutation( iterator start, iterator end );

The next_permutation() function attempts to transform the given range of elements [start,end) into the next lexicographically greater permutation of elements. If it succeeds, it returns true, otherwise, it returns false.

从说明中可以看到 next_permutation 的返回值是布尔类型。

注意说明中说的前闭后开区间;

下面是我打的一段程序说明函数:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <string>
 4 #include <functional>
 5 using namespace std;
 6  
 7 int main()
 8 {
 9     string str;
10     cin >> str;
11     long long  ans=1;
12     sort(str.begin(), str.end(),less<char>());//升序排列
13     cout << str << endl;
14     while (next_permutation(str.begin(), str.end()))
15     {
16         cout << str << endl;
17         ans++;
18     }
19     cout<<"the next string:"<<str<<endl;
20     cout<<"total forms:"<<ans<<endl;
21     return 0;
22 }
23 //在STL中,除了next_permutation外,还有一个函数prev_permutation,
24 //两者都是用来计算排列组合的函数。前者是求出下一个排列组合,而后者
25 //是求出上一个排列组合。所谓“下一个”和“上一个”,书中举了一个简单的例子:
26 //对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比bc都小,
27 //c比b大,它的下一个序列即为{a, c, b},而{a, c, b}的上一个序列即为{a, b, c},
28 //同理可以推出所有的六个序列为:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},
29 //其中{a, b, c}没有上一个元素,{c, b, a}没有下一个元素。
30 /*
31 用next_permutation和prev_permutation求排列组合很方便,
32 但是要记得包含头文件#include <algorithm>。
33 虽然最后一个排列没有下一个排列,用next_permutation会返回false,
34 但是使用了这个方法后,序列会变成字典序列的第一个,如cba变成abc。prev_permutation同理。
35 */
代码+说明

相关文章: