用递归实现排列组合

来源:互联网 发布:神经网络算法 编辑:程序博客网 时间:2024/05/21 09:43
#include <iostream>/* *用递归实现排列组合 */void Permutation(char *p,const int k,const int m){    if(k==m)  //递归终止条件    {        printf("%s\n",p);    }    for(int i=k;i<=m;i++)    {        std::swap(p[k],p[i]);        Permutation(p,k+1,m);        std::swap(p[k],p[i]);    }    /*  下面是递归过程    //a开头, 后面跟着bc的所有排列    swap(p[0],p[0]);    Permutation(p,1,2);    swap(p[0],p[0]);    //b开头的,后面跟着ac的所有排列    swap(p[0],p[1]);    Permutation(p,1,2);    swap(p[0],p[1]);    //c开头的,后面跟着ab的所有排列    swap(p[0],p[2]);    Permutation(p,1,2);    swap(p[0],p[2]);    */}int main(){    char s[]="abc";    Permutation(s,0,2);    system("pause");    return 0;}

0 0
原创粉丝点击