输出数组的全排列方法

参考:点击打开链接

1 递归方法求全排列

// 数组的全排列.cpp : 定义控制台应用程序的入口点。
//程序猴6.27

#include "stdafx.h"
template void Swap(T &A,T &B)
{
	T Tmp = A;
	A = B;
	B = Tmp;
}

//判重复元素函数,如果第[Begin,End)之间有元素和第End元素相等,则不执行交换Begin和End元素,
//因为交换它两与交换Begin和End之前与End元素相同的元素产生的结果一致
template bool IsSwap(T A[],int Begin,int End)
{
	while(Begin void Permutation(T A[],int Begin,int N)
{
	if (Begin == N)
	{
		for(int i=0;i


2 非递归算法

template void ReverseTail(T A[],int Begin,int End) //摆尾
{
	while(Begin bool NextPermutation(T A[],int N)
{
	if (N==1)
	  return false;
	int p,q,End,Find;
	End = N-1;
	p = End;
	while (p!=0)
	{
		q = p;
		p--;
		if (A[p]=A[Find])
				Find--;
			Swap(A[p],A[Find]);
			ReverseTail(A,q,End);  //反转q~End元素,方便再次查找全排列
			return true;
		}
	}
	ReverseTail(A,0,End);
	return false;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int A[5] = {5,1,2,4,2};
	int N = 5;
    //Permutation(A,0,N);
	QuickSort(A,N); //先将原始序列排序
	printf("排序后的原始序列\n");
	for(int i=0;i


运行结果:

输出数组的全排列方法_第1张图片

你可能感兴趣的:(数据结构与算法)