next_permutation函数用法举例

按照STL文档的描述,next_permutation函数将按字母表顺序生成给定序列的下一个较大的排列,直到整个序列为降序为止。prev_permutation函数与之相反,是生成给定序列的上一个较小的排列。

这是一个求一个排序的下一个排列的函数,可以遍历全排列,要包含头文件<algorithm>

使用方法:next_permutation(数组头地址,数组尾地址);若下一个排列存在,则返回真,如果不存在则返回假

若求上一个排列,则用prev_permutation

1.举例

int main()
{
    int num = 1,a[6]= {1,2,3,4,5};
    while(next_permutation(a,a+5))
    {
        for(int i=0; i<5; i++)
            cout<<a[i]<<" ";
        if(num==5)
            break;
        num++;
        cout<<endl;
    }
    return 0;
}

 

2.字符串(字母数组)

 

int main()
{
    string str = "abcde";
    int num = 1;
    while(next_permutation(str.begin(),str.end()))
    {
        num++;
        cout<<str<<endl;
        if(num==5)
            break;
    }
    return 0;
}

在这里补充一道题目HDU - 1716 

Ray又对数字的列产生了兴趣: 
现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。

Input

每组数据占一行,代表四张卡片上的数字(0<=数字<=9),如果四张卡片都是0,则输入结束。 

Output

对每组卡片按从小到大的顺序输出所有能由这四张卡片组成的4位数,千位数字相同的在同一行,同一行中每个四位数间用空格分隔。 
每组输出数据间空一行,最后一组数据后面没有空行。 

Sample Input

1 2 3 4
1 1 2 3
0 1 2 3
0 0 0 0

Sample Output

1234 1243 1324 1342 1423 1432
2134 2143 2314 2341 2413 2431
3124 3142 3214 3241 3412 3421
4123 4132 4213 4231 4312 4321

1123 1132 1213 1231 1312 1321
2113 2131 2311
3112 3121 3211

1023 1032 1203 1230 1302 1320
2013 2031 2103 2130 2301 2310
3012 3021 3102 3120 3201 3210

这里就先对四个数字进行排序,然后用next_permutation函数寻找四个数字的全排列,需要注意的是格式问题,每一行的最后一个数后面没有空格,最后一组数据后面没有空行。我是用一个数组将所有符合条件的四位数存起来,然后进行输出,这样便于控制格式。

AC代码

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
    int s[4],num[25];
    int cnt = 0;
    while(scanf("%d%d%d%d",&s[0],&s[1],&s[2],&s[3]) && s[0] + s[1] + s[2] + s[3])
    {
        if(cnt++)
            printf("\n");
        int k = 1;
        memset(num,0,sizeof(num));
        sort(s,s+4);
        for(int i=0; i<4; i++)
            num[k] = num[k] * 10 + s[i];
        while(next_permutation(s,s+4))
        {
            k++;
            for(int i=0; i<4; i++)
            {
                num[k] = num[k] * 10 + s[i];
            }
            //printf("%d\n",num[k]);
        }
        int t = 1,p;
        while(num[t]<1000)
            t++;
        printf("%d",num[t]);
        p = num[t] / 1000;
        //printf("%d\n",p);
        for(int i=(++t); i<=k; i++)
        {
            if(((num[i] / 1000) > p))
            {
                p = num[i] / 1000;
                printf("\n%d",num[i]);
            }
            else
                printf(" %d",num[i]);
        }
        printf("\n");
    }
    return 0;
}

 

  • 53
    点赞
  • 210
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值