您的位置:首页 > 其它

next_permutation()

2016-11-11 19:51 197 查看
next_permutation()是一个过程,

也是一个函数,

需要#include <algorithm>

next_permutation(a,a+k); 从a[0]开始,对总共k个数进行升序排序;

next_permutation(a+i,a+n); 从a[i]开始,一直排到a
;

感觉很奇怪, 这里有点问题

因为按照这么理解

第一个函数应该是从a[0]排到a[k],总共k+1个数,这就尴尬了

但是实验下来,确实这么用,无语

1 int main()
2 {
3 int a[3];
4 a[0]=1;a[1]=2;a[2]=3;
5 do
6 {
7 cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
8 } while (next_permutation(a,a+3)); 参数3指的是要进行排列的长度
9
10 如果a不是最大的排列,就返回true。如果a是最大的排列,返回false,
11 每执行一次,a就变成下一个更大的排列
12
13 }
14
15 输出:
16
17  1 2 3
18  1 3 2
19  2 1 3
20  2 3 1
21  3 1 2
22  3 2 1
23
24
25 如果改成 while(next_permutation(a,a+2));
26 则输出:
27  1 2 3
28  2 1 3
29
30 只对前两个元素进行字典排序
31
32 显然,如果改成 while(next_permutation(a,a+1)); 则只输出:1 2 3
33
34
35 若排列本来就是最大的了,则next_permutation执行后,会对排列进行字典升序排序
36
37 int list[3]={3,2,1};
38 next_permutation(list,list+3);
39 cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<endl;
40
41 输出: 1 2 3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: