输入n,输出所有的n元排列

/*
问题描述:
输入n,输出所有的n元排列
*/
#include <iostream>
using namespace std;

void GenerateFullPer(int *const p,bool* const hashtable,int index,int const n);

void output(int *p,int n)
{
	for (int i=1;i<=n;i++)
	{
		cout<<p[i]<<" ";
	}
	cout<<endl;
}

void GenerateFullPer(const int n)
{
	int * p=new int[n+1];          //数组p保存暂时生成的结果
	bool *hashtable=new bool[n+1]; //hashtable[i]==true表示元素i已经在该排列中
	memset(p,0,(n+1)*sizeof(int));
	memset(hashtable,0,sizeof(bool)*(n+1));
	
	GenerateFullPer(p,hashtable,1,n);

	delete []p;
	delete []hashtable;
}

void GenerateFullPer(int *const p,bool* const hashtable,int index,int const n)
{
	if (index>n)//代码走到这里已经生成了一个全排列
	{
		output(p,n);
		return;
	}

	for (int i=1;i<n+1;i++)
	{
		if (hashtable[i]==false)
		{
			hashtable[i]=true;
			p[index]=i;
			GenerateFullPer(p,hashtable,index+1,n);//处理下一个位置
			hashtable[i]=false;//index位置上为i的情况处理完,释放i,再在index位置上尝试其他值
		}
	}

}


int main()
{
	GenerateFullPer(10);
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/qq_27012559/article/details/79742519