求{1,2,3}序列的全排列

来源:互联网 发布:ug8.钻孔怎么编程 编辑:程序博客网 时间:2024/06/08 06:00

博主从来都不多说废话,直接上代码!!!

#include<iostream>using namespace std;template<class Type>void Swap(Type &a,Type &b)//交换函数{    Type c = a;    a = b;    b = c;}void Perm(int *ar,int k,int m){    if(k == m)    {        for(int i = 0;i<=m;++i)        {            cout<<ar[i]<<" ";        }        cout<<endl;    }    else    {        for(int j = k ; j<=m;++j)        {            Swap(ar[k],ar[j]);            Perm(ar,k+1,m);//注意:是k+1,不要写成k++            Swap(ar[k],ar[j]);//交换回去        }    }}void main(){    int ar[]={1,2,3};    int n = sizeof(ar)/sizeof(ar[0]);    Perm(ar,0,n-1);}

程序运行结果

//代码非常简洁,小伙伴们看懂了吗??
//下面给出一张排列树的图片,方便大家理解
这里写图片描述

原创粉丝点击