排列组合 用递归

#include <iostream>

using namespace std;

int c1 = 0;  // 调用的次数,
int c2 = 0;  // 返回的次数,

void show(char *p, int m)
{
	for(int i = 0; i <= m; i++)
		cout << p[i];
	cout << endl;
}

void Permutations(char *p, const int k, const int m) // permutation排序,
{
	cout << "c1 = " << ++c1 << endl;
	if(k == m)
	{
		for(int i = 0; i <= m; i++)
			cout << p[i];
		cout << endl;
	}
	else
	{
	    for(int i = k; i <= m; i++)
		{
			cout << "递归前,交换前: ";
			show(p,m);
			swap(p[k],p[i]);
			cout << "递归前,交换后:";
			show(p,m);
			Permutations(p,k + 1,m);
			cout << "c2 = " << ++c2 << endl;
			cout << "递归后,交换前:";
			show(p,m);
			swap(p[k],p[i]);
			cout << "递归后,交换后:";
			show(p,m);
		}
	}
	//// a开头的,后面跟着bc的所有排序
	//swap(p[0],p[0]);
	//Permutations(p,1,2);
	//swap(p[0],p[0]);
	//// a开头的,后面跟着bc的所有排序
	//swap(p[0],p[1]);
	//Permutations(p,1,2);
	//swap(p[0],p[1]);
	//// a开头的,后面跟着bc的所有排序
	//swap(p[0],p[2]);
	//Permutations(p,1,2);
	//swap(p[0],p[2]);
}

int main()
{
	char s[] = "abc";
	Permutations(s,0,2);


	return 0;
}

你可能感兴趣的:(排列组合 用递归)