C++ 求排列函数 next_permutation, prev_permutation

今天在POJ上遇到了一个题目,我想的解题思路里面需要求出一个数组中所有的排列情况,自己想了半天,觉得实现很复杂,于是搜索一下,才发现有next_permutation这个方法。

简单的介绍一下,next_permutation能生成下一个字典集更大一点的排列, 而prev_permutation则刚好相反,生成下一个字典集更小一点的排列。

下面是一个示例,里面有一些关于next_permutation()函数的用法示例

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

void TestCharArray(){
    cout << "Test char array:" << endl;
    char chs[] = {'3','5','4','6'};
    int number = sizeof(chs)/sizeof(char);

    //next_permutation()需要两个参数,参数1:要开始排列的元素的指针, 参数2:要结束排列的元素的指针 
    //之调用一次,就生成一个比上一个字典序大的排列 
    next_permutation(chs + 0, chs + number);
    for(int i = 0; i < number; i++){
            cout << chs[i] << "\t";
    }
    cout << endl; 

    //通过这种方式一直调用,当字典序达到最大,也就是减序的时候,next_permutation()返回false 
    do{
        for(int i = 0; i < number; i++){
            cout << chs[i] << "\t";
        }
        cout << endl;
    }while(next_permutation(chs + 0, chs + number));//注意这里有个分号 
}

void TestIntArray(){
    cout << "test int array:"<< endl;
    int a[] = {1, 2, 3, 4};
    int number = sizeof(a) / sizeof(int);
    do{
        for(int i = 0; i < number; i++){
            cout << a[i] << "\t";
        }
        cout << endl;
    }while(next_permutation(a, a + number));
}
void TestString(){
    cout << "test string:" << endl;
    string s = "abcd";
    do{
        cout << s << endl;
    }while(next_permutation(s.begin(), s.end()));
} 
int main(){
    TestCharArray();
    TestString();
    TestIntArray();
}

ps: 如果next_permutation函数生成的字典集不是最大的,它就会返回true,所以上面的循环才能一直进行下去,直到排列成字典集最大的情况,然后返回false。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值