algorithm中的next_permutation函数

这个函数是按照字典序用来生成全排列,做一些枚举,搜索啊这些很暴力的时候很有用,特别是需要字典序输出的时候,以前很苦恼的字典序问题用现在的方法,好像可以解决了。。

先来看一个例子:

#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

至于它的用法。。下次找个题目来做一下,熟悉一下好了~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值