Contents
  1. 1. C++中的全排列函数使用方法

C++中的全排列函数使用方法

  • 使用前对数组从小到大排好序
  • 用while语句判断其是否还有下一个全排列存在
  • 补:N个元素(不同的)的全排列总数为n!个。
    如果有相同的元素就把那个元素个数的阶乘给除掉,具体看hdu5651
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53


    //实例一:
    #include <cstdio>
    #include <iostream>
    #include <algorithm>

    using namespace std;

    void permutation(int a[], int len)
    {

    int i;
    sort(a, a + len); //用这个全排列之前,要先对它排序
    do{
    for(i = 0; i < len; i++)
    cout << a[i] << " ";
    cout << endl;
    }while(next_permutation(a, a + len));//如果返回true,则生成下一个全排列
    }

    int main()
    {

    int a[4] = {1, 2, 3, 4};
    permutation(a, sizeof(a) / sizeof(a[0]));
    return 0;
    }



    //实例二:

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

    int main()
    {

    string str;
    cout << "Please enter the str grouping (quit to quit): ";
    while(cin >> str && str != "quit")
    {
    cout << "Permutations of " << str << endl;
    sort(str.begin(), str.end());
    cout << str << endl;
    while(next_permutation(str.begin(), str.end()))
    cout << str << endl;
    cout << "Enter next sequence (quit to quit): ";
    }
    cout << "Done.\n";
    return 0;
    }
Contents
  1. 1. C++中的全排列函数使用方法