我们经常会遇到这样的问题。
 example:我们有三个数 1 2 3,要求输出他们的全排列并按照字典序的顺序。
             123
             132
             213
             231
             312
             321
 通常的做法是写个函数然后递归解决。
 这次我来介绍两个函数 next_permutation 和 prev_permutation
next_permutation是求出当前排列的下一个排列,它的返回值是0或1
 它需要两个参数,第一个是起始地址,第二个是结束地址。 next_permutation(a, a+n);
 比如现在是123 用一次 next_permutation就变成了,返回值是1
 如果是321了,因为没有下一个返回值就是0
同理 prev_permutation是求出当前排列的上一个排列,返回值也是0或1
code:
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp1(int a, int b)
{
    if(a < b)
        return 1;
    return 0;
}
bool cmp2(int a, int b)
{
    if(a > b)
        return 1;
    return 0;
}
int main()
{
    int a[100];
    for(int i=0; i<3; i++)
    {
        cin >> a[i];
    }
    sort(a, a+3, cmp1);     // 先排序成从小到大
    do{
        for(int i=0; i<3; i++)
            cout << a[i];
        cout << endl;
    }while(next_permutation(a, a+3));
    cout << endl;
    sort(a, a+3, cmp2);
    do{
        for(int i=0; i<3; i++)
            cout << a[i];
        cout << endl;
    }while(prev_permutation(a, a+3));
    return 0;
}  

京公网安备 11010502036488号