8、排列组合

  1 /*
  2 Permutations
  3 排列组合
  4 输入abc,输出所有可能的排列结果
  5 输入:abc
  6 输出:	abc
  7 		acb
  8 		bac
  9 		bca
 10 		cab
 11 		cba
 12 */
 13 
 14 #include<iostream>
 15 
 16 using namespace std;
 17 
 18 int c1=0;
 19 int c2=0;
 20 
 21 void show(char *p,int m)
 22 {
 23 	for(int i=0;i<=m;i++)
 24 		cout<<p[i];
 25 	cout<<endl;
 26 }
 27 
 28 void Permutations(char *p,const int k,const int m)
 29 {
 30 	cout<<"c1="<<++c1<<endl;//进入递归一共调用了10次
 31 	if(k==m)
 32 	{
 33 		for(int i=0;i<=m;i++)
 34 			cout<<p[i];
 35 		cout<<endl;
 36 	}
 37 	else
 38 	{
 39 		for(int i=k;i<=m;i++)
 40 		{
 41 			cout<<"递归前,交换前";
 42 			show(p,m);
 43 			swap(p[k],p[i]);
 44 			cout<<"递归前,交换后";
 45 			show(p,m);
 46 			Permutations(p,k+1,m);
 47 			cout<<"c2="<<++c2<<endl;//返回递归的次数
 48 			cout<<"递归后,交换前";
 49 			show(p,m);
 50 			swap(p[k],p[i]);
 51 			cout<<"递归后,交换后";
 52 			show(p,m);
 53 		}
 54 	}
 55 	////a开头的,后面跟着bc的所有排列
 56 	//swap(p[0],p[0]);
 57 	//Permutations(p,1,2);
 58 	//swap(p[0],p[0]);
 59 	////a开头的,后面跟着bc的所有排列
 60 	//swap(p[0],p[1]);
 61 	//Permutations(p,1,2);
 62 	//swap(p[0],p[1]);
 63 	////a开头的,后面跟着bc的所有排列
 64 	//swap(p[0],p[2]);
 65 	//Permutations(p,1,2);
 66 	//swap(p[0],p[2]);
 67 }
 68 
 69 int main()
 70 {
 71 	char s[]="abc";
 72 	Permutations(s,0,2);
 73 
 74 	system("pause");
 75 	return 0;
 76 }
 77 


VS2010运行结果:

image

posted @ 2018-04-18 17:03  乱丶心  阅读(254)  评论(0编辑  收藏  举报