• 生成1~n的排列(模板),生成可重集的排列(对应紫书P184, P185)


    生成1~n的排列:

    #include<iostream>
    using namespace std;
    void print_permutation(int n, int *A, int cur)      /*n代表这个排列中的元素数*/
    {
        if(cur == n)    /*边界*/
        {
            for(int i = 0; i < n; i++)
                cout << A[i] << " ";
            cout << endl;
        }
        else
            for(int i = 1; i <= n; i++)     /*在A中插入1~n这几个数*/
            {
                int ok = 1;
                for(int j = 0; j < cur; j++)
                {
                    if(A[j] == i)
                        ok = 0;             /*从前的元素中已经含有i这个数时,就不再插入它*/
                }
                if(ok)
                {
                    A[cur] = i;
                    print_permutation(n, A, cur + 1);           /*递归*/
                }
            }
    }
    int main()
    {
        const int maxn = 200;
        int A[maxn];
        print_permutation(5, A, 0);        /*生成由1~5组成的全排列,cur初始值设为0*/
    }
    

    生成可重集的排列:

    #include<iostream>
    #include<algorithm>
    using namespace std;
    void print_permutation(int n, int *P, int *A, int cur)
    {
        if(cur == n)
        {
            for(int i = 0; i < n; i++)
                cout << A[i] << " ";
            cout << endl;
        }
        else
            for(int i = 0; i < n; i++)
            {
                if(!i || P[i] != P[i-1])
                {
                    int c1 = 0, c2 = 0;
                    for(int j = 0; j < cur; j++)
                    {
                        if(A[j] == P[i])
                            c1++;           /*看A中有多少与P[i]相同的元素*/
                    }
                    for(int j = 0; j < n; j++)
                    {
                        if(P[i] == P[j])
                            c2++;           /*看P中有多少与P[i]相同的元素*/
                    }
                    if(c1 < c2)     /*P中的那个元素还没用或还没用完,则将它存入数组A中*/
                    {
                        A[cur] = P[i];
                        print_permutation(n, P, A, cur + 1);
                    }
                }
            }
    }
    int main()
    {
        const int maxn = 200;
        int P[maxn], A[maxn];
        int n;
        cin >> n;
        for(int i = 0; i < n; i++)
            cin >> P[i];
        sort(P, P + n);
        print_permutation(n, P, A, 0);
    }
    

    这个大佬讲的更多些

  • 相关阅读:
    python模块--time模块
    python模块--如何相互调用自己写的模块
    Animating Views Using Scenes and Transitions
    fragment 切换
    android textview 设置text 字体
    android intent 5.1
    android EditView ime
    animation of android (4)
    animation of android (3)
    animation of android (2)
  • 原文地址:https://www.cnblogs.com/KeepZ/p/11143776.html
Copyright © 2020-2023  润新知