C++全排列函数next_permutation()和prev_permutation()

头文件:#include

*

1. next_permutation():

next_permutation()函数的返回类型是bool类型.

即:如果有一个更高的排列,它重新排列元素,并返回true;如果这是不可能的(因为它已经在最大可能的排列),它按升序排列重新元素,并返回false。

使用:

next_permutation,重新排列范围内的元素[第一,最后一个)返回按照字典序排列的下一个值较大的组合。

next_permutation()函数功能是输出所有比当前排列大的排列,顺序是从小到大

算法描述:

从尾部开始往前寻找两个相邻的元素

第1个元素i,第2个元素j(从前往后数的),且i<j

2、再从尾往前找第一个大于i的元素k。将i、k对调

3、[j,last)范围的元素置逆(颠倒排列)

2. prev_permutation():

prev_permutation()函数功能是输出所有比当前排列小的排列,顺序是从大到小

例:

K—排列2

Ray又对数字的列产生了兴趣:

现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。

Input每组数据占一行,代表四张卡片上的数字(0<=数字<=9),如果四张卡片都是0,则输入结束。

Output对每组卡片按从小到大的顺序输出所有能由这四张卡片组成的4位数,千位数字相同的在同一行,同一行中每个四位数间用空格分隔。

每组输出数据间空一行,最后一组数据后面没有空行。

Sample Input

1 2 3 4
1 1 2 3
0 1 2 3
0 0 0 0Sample Output
1234 1243 1324 1342 1423 1432
2134 2143 2314 2341 2413 2431
3124 3142 3214 3241 3412 3421
4123 4132 4213 4231 4312 4321

1123 1132 1213 1231 1312 1321
2113 2131 2311
3112 3121 3211

1023 1032 1203 1230 1302 1320
2013 2031 2103 2130 2301 2310
3012 3021 3102 3120 3201 3210






代码:

#include<iostream>
#include<algorithm>    //next_permutation
using namespace std;
int deal(int n)
{
   int sum=1;
   for (int i=1;i<=n;i++)
        sum*=i;
        return sum;
}
int main()
{
    int x[5],f,flag=0;
    while (1)
    {

        cin>>x[0]>>x[1]>>x[2]>>x[3];
        if(x[0]==0&&x[1]==0&&x[2]==0&&x[3]==0)
            return 0;

      if(flag!=0)
        cout << endl;
        flag=1;
        int w=0;
        sort(x,x+4);   //排序,默认升序,头文件algorithm
        f=0;
      do
      {
          if (x[0]==0)
            continue;
            if (f==0)
            {
                cout << x[0] << x[1] << x[2] << x[3] ;
                f=1;
            }
            else
            {
                if (w==x[0])
                    cout << ' ' << x[0] << x[1] << x[2] << x[3] ;
                else
                    cout << endl  << x[0] << x[1] << x[2] << x[3]  ;

            }
            w=x[0];
      }
      while (next_permutation(x,x+4));
  cout << endl;
    }
    return 0;
}

注意输出格式:是输入一组数据后换行输出结果
原文链接: https://www.cnblogs.com/lisijie/p/7193861.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/256874

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午10:29
下一篇 2023年2月14日 上午10:30

相关推荐