用程序实现全排列(二)

反思:

1.Q:next_permutation如何处理有重复串的情况?

   A:上述函数实现的原理仍然适用:

对于{1,1,1,1,1},由于找不到一个正序对,所以next_permutation返回false;

2.Q:是否有求出前一个排列的函数?

   A:prev_permutation

参数,返回值,实现原理等类似

(二)自己写一个交换的程序

代码如下:

#include<iostream>
#include<cstdio>
#include<string>
#include<string.h>
#include<cstring>
#include<algorithm>

using namespace std;
void exchange(int*,int,int);
int cnt = 0;
int main()
{
    int Array[5] = {1,2,3,4,5};
    int subarray[5];
    memset(subarray,0,sizeof(subarray));
   /* for(int i = 0; i < 5; ++i)
    {
        printf("%d	",Array[i]);
    }*/
    printf("
");
    exchange(Array,5,0);
    cout << cnt << endl;
    return 0;
}
void exchange(int*a,int len,int index)
{
    if(index == len)
    {
        ++cnt;
        for(int i = 0; i < len; ++i)
        {
            printf("%d	",a[i]);
        }
        printf("
");
    }
    for(int i = index; i < len; ++i)
    {
        int tmp = a[i];
        a[i] = a[index];
        a[index] = tmp;

        exchange(a,len,index+1);

        tmp = a[i];
        a[i] = a[index];
        a[index] = tmp;
    }
}

  但这种交换的方法不能保证按字典序递增输出全排列,同时也不能处理有重复字符串的情况

fringe benefit:学会了打数学符号:用软件盘:)

以及手写的三行交换居然写错了= =,看来STL或封装还是很有必要的,否则在大程序里这么小的bug貌似影响会很大又很难找到错误

原文地址:https://www.cnblogs.com/warmfrog/p/3645745.html