next_permutation函数初识

#include <iostream>
#define MAX_M 10
#define MAX_N 10
using namespace std;
bool used[MAX_N];
int perm[MAX_M];

//  生成{1,2,3,4,....,n-1}的n!种排列

void permutation1(int pos,int n){
    if (pos == n){
        cout << n << ' ';
        return ;
    }
    //  针对perm的第pos个位置,究竟使用0~n-1中的哪个循环
    for (int i = 0;i < n;i ++){
        if (!used[i]){
            perm[pos] = i;
            //  i已经被使用过了,所以把标志设置为true
            used[i] = true;
            permutation1(pos + 1,n);
            //  返回之后把标志复位
            used[i] = false;
        }
    }
    return ;
}

#include <algorithm>

//  即使有重复元素也会生成所有的排列
//  next_permutation是按照字典序来生成下一个排列的
int perm2[MAX_N];

void permutation2(int n){
    for (int i = 0;i < n;i ++)
        perm2[i] = i;
    do {
        cout << n << ' ';
    } while (next_permutation(perm2,perm2 + n));
    //  所以排列都生成后,next_permutation会返回false
    return ;
}

int main()
{
    permutation1(7,10); // 生成 10!/7!
    permutation2(8);    // 生成8!
}

上面的代码可能有点难懂,那么我们现在就看一下新型的代码

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

struct Rule{
    bool operator()(char & a,char & b){
    return a > b;
    }
};

int main()
{
    char ch[205];
    cin >> ch;

    sort(ch,ch+strlen(ch),Rule());

    char *first = ch;
    char *last = ch + strlen(ch);

    do{
        cout << ch << endl;
    }while (next_permutation(ch,ch+3,Rule()));
}

其中上面的表达式,next_permutation 可以用地址,或者是迭代器(指针)来实现,并且,可以自定义实现的结果。

第一个大神的链接

第二个大神的链接


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值