zoukankan      html  css  js  c++  java
  • 递归实现全排列(一)

    【思路】

    以下用详细样例来阐述这样的实现的思路,比如实现123的全排列组合。
    要求123的全排列,能够分为以下情况:
    情况1:第0位为1+23的全排列
    情况2:第0位为2+13的全排列
    情况3:第0位为3+32的全排列
    上面的情况用代码实现例如以下:

    //情况1
    //为了跟以下一致,加上swap(list[0],list[0]);
    perm(list,1,2);
    //为了跟以下一致,加上swap(list[0],list[0]);
    
    //情况2
    swap(list[0],list[1]);
    perm(list,1,2);
    swap(list[0],list[1]);
    
    //情况3
    swap(list[0],list[2]);
    perm(list,1,2);
    swap(list[0],list[2]);

    这3种情况能够用循坏取代:

    for(int i=0;i<=2;i++)
    {
      swap(list[0],list[i]);
      perm(list,1,2);
      swap(list[0],list[i]);
    }

    【全排列实现代码一】

    #include<iostream>
    using namespace std;
    void perm(char list[],int k,int m);
    void perm(char list[],int k,int m)
    {
        if(k==m)
        {
           for(int j=0;j<=m;j++)
           {
            cout<<list[j];
           }
           cout<<endl;
        }
        else
        {
         for(int i=k;i<=m;i++)
         {
          std::swap(list[k],list[i]);
          perm(list,k+1,m);
          std::swap(list[k],list[i]);
         }
        }
    }
    int main()
    {
        char a[]="123";
        perm(a,0,2);
        system("pause");
        return 0;
    }
  • 相关阅读:
    学习Tomcat(三)
    TIME_WAIT 优化注意事项
    TIME_WAIT 优化
    TCP(一)
    TCP(二)
    TCP(三)
    5-14 练习题及答案
    5-14 进程池
    5-11 操作系统介绍
    5-8套接字socket
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6744184.html
Copyright © 2011-2022 走看看