C++STL的next_permutation
2016-08-28 15:12
453 查看
这是一个求一个排序的下一个排列的函数,可以遍历全排列,要包含头文件<algorithm>
与之完全相反的函数还有prev_permutation
在STL中,除了next_permutation外,还有一个函数prev_permutation,两者都是用来计算排列组合的函数。
前者是求出下一个排列组合,而后者是求出上一个排列组合。所谓“下一个”和“上一个”,书中举了一个简单的例子:
对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比bc都小,c比b大,它的下一个序列即为{a, c, b},而{a, c, b}的上一个序列即为{a, b, c},同理可以推出所有的六个序列为:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}没有上一个元素,{c, b, a}没有下一个元素。
[b](1) int 类型的next_permutation[/b]
输出
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
[b]如果改成 while(next_permutation(a,a+2));[/b]
则输出:
1 2 3
2 1 3
[b]只对前两个元素进行字典排序
显然,如果改成 while(next_permutation(a,a+1)); 则只输出:1 2 3[/b]
[b][b](2)char 类型的next_permutation[/b][/b]
与之完全相反的函数还有prev_permutation
在STL中,除了next_permutation外,还有一个函数prev_permutation,两者都是用来计算排列组合的函数。
前者是求出下一个排列组合,而后者是求出上一个排列组合。所谓“下一个”和“上一个”,书中举了一个简单的例子:
对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比bc都小,c比b大,它的下一个序列即为{a, c, b},而{a, c, b}的上一个序列即为{a, b, c},同理可以推出所有的六个序列为:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}没有上一个元素,{c, b, a}没有下一个元素。
[b](1) int 类型的next_permutation[/b]
#include<iostream> #include<stdio.h> #include<queue> #include<string> #include<string.h> #include<algorithm> using namespace std; int main() { int a[3]={1,2,3}; do { cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl; }while(next_permutation(a,a+3)); return 0; }
输出
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
[b]如果改成 while(next_permutation(a,a+2));[/b]
则输出:
1 2 3
2 1 3
[b]只对前两个元素进行字典排序
显然,如果改成 while(next_permutation(a,a+1)); 则只输出:1 2 3[/b]
[b][b](2)char 类型的next_permutation[/b][/b]
#include<iostream> #include<stdio.h> #include<queue> #include<string> #include<string.h> #include<algorithm> using namespace std; int main() { char ch[205]; cin>>ch; sort(ch,ch+strlen(ch)); char *first =ch; char *last=ch+strlen(ch); do{ cout<<ch<<endl; }while(next_permutation(first,last)); return 0; }
相关文章推荐
- C++ STL之next_permutation小证明与Java实现
- C++STL的next_permutation
- C++STL的next_permutation 的用法
- C++STL中全排列函数next_permutation的使用
- Orders(C++ stl next_permutation)
- 自己实现了一下C++STL中的next_permutation,名为ant_next_permutation,发下代码
- C++STL的next_permutation
- C++STL的next_permutation
- C++ STL, next_permutation用法。
- C++STL中全排列函数next_permutation的使用
- C++ STL next_permutation() prev_permutation(a,a+n)用法。
- 【C++ STL应用与实现】62: 如何使用std::next_permutation
- C++ STL next_permutation() & prev_permutation()函数
- C++ STL next_permutation的实现原理
- C++ STL next_permutation
- C++ STL next_permutation的实现原理
- STL源码学习----next_permutation和prev_permutation算法
- STL的应用 multiset bitset next_permutation
- HDU-1027 组合数 STL-next_permutation
- STL:next_permutation (UVaOJ 146)