美文网首页
递归-全排列

递归-全排列

作者: Co_zy | 来源:发表于2018-04-03 18:33 被阅读0次

    对数组{1,2,3}进行全排列

    #include <iostream>
    using namespace std;
    void swap(int a[],int i,int j)
    {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
    void printArray(int a[],int n)
    {
        for(int i=0; i<n; i++)
            cout<<a[i]<<" ";
        cout<<endl;
    }
    void perm(int a[],int p,int q)
    {
        if(p==q)
            printArray(a,q+1);
        for(int i=p; i<=q; i++)
        {
            swap(a,p,i);
            perm(a,p+1,q);
            swap(a,p,i);
        }
    }
    int main()
    {
        int a[] = {1,2,3};
        perm(a,0,2);
        return 0;
    }
    

    STL next_permutation

    #include <algorithm>
    int main()
    {
        int a[] = {1,2,3};
        //perm(a,0,2);
        do
        {
            for(int i=0;i<3;i++)
                cout<<a[i]<<" ";
            cout<<endl;
        }while(next_permutation(a,a+3));
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:递归-全排列

          本文链接:https://www.haomeiwen.com/subject/prpchftx.html