全排列函数next_permutation与prev_permutation

C++ 全排列函数 next_permutation与prev_permutation
C++ STL中提供了next_permutation与prev_permutation可以获取数字或者是字符的全排列,其中next_permutation提供升序、prev_permutation提供降序。
1.next_permutation(first,last)
说明:对[first,last)区间进行排列,第一次输出当前的排列顺序,例如:1234,第二次输出比第一次大的下一种排列,则为1243(若为数组,则通过数字比较来判断大小,若为字符串,则通过ASCII码来比较大小)。

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

int main()
{
    int a[100];
    int n=0,i;
    while(cin>>a[n])
        n++;
    sort(a,a+n);
    //输出升序的全排列则应将最初的数组排为最小顺序
    //如1 4 3 2 ,则应先排为1 2 3 4 使next_premutation()
    //正常输出
    do
    {
        for(i=0;i<n-1;i++)
            cout<<a[i];
        cout<<a[i]<<endl;
    }while(next_permutation(a,a+n));

    return 0;
}

2.next_permutation( first , last , cmp)
说明:我们可以通过改变cmp()函数来改变next_permutation()函数产生的到底是升序全排列还是,降序全排列。在不写cmp()函数时,next_permutation()默认为升序全排列。

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

bool cmp(int a,int b)
{
    return a>b;//a>b为降序,a<b为升序。
}

int main()
{
    int a[100];
    int n=0,i;
    while(cin>>a[n])
    {
        n++;
    }
    sort(a,a+n,cmp);//sort()也应该为降序。
    do
    {
        for(i=0;i<n-1;i++)
            cout<<a[i];
        cout<<a[i]<<endl;
    }while(next_permutation(a,a+n,cmp));//输出降序全排列

    return 0;
}

3.prev_permutation( first , last )与prev_permutation( first , last , cmp)的用法与前两项相同,这里就不过多赘述。
4.用next_permutation()对字符串进行排序。

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

int main()
{
    string str;
    cin>>str;
    sort(str.begin(),str.end());
    do
    {
        cout<<str<<endl;
    }while(next_permutation(str.begin(),str.end()));
//原理相同。
    return 0;
}

4.题目:字符的全排列(顺序:’A’<’a’<’B’<’b’<…<’Z’<’z’)。

#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;

int val(char c)    // 按照'A'<'a'<'B'<'b'<...<'Z'<'z'的顺序,每个字母赋一个固定的权值。
{
    if(c >= 'A' && c <= 'Z') 
        return 2 * (c - 'A');
    else 
        return 2 * (c - 'a') + 1;
}

bool cmp(char a, char b)
{
    return val(a) < val(b);
}

int main()
{
    char str[100];
    cin >> str;
    int n = strlen(str);
    sort(str, str + n, cmp);
    do
    {
        cout << str << endl;
    }
    while(next_permutation(str, str + n, cmp));

    return 0;
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值