【IT面试题004】全排列

使用深度优先搜索

/*

套用深度优先搜索之全排列
全排列 

输入: n(<=26)
输出:将 前n个小写字母全排列输出
*/

#include "stdafx.h"

#include <iostream>

#include <string>
#include <vector>
using namespace std;

int gN;
const int MAX_ELEMENT = 10000;
char solution[MAX_ELEMENT];
int selected[26];
int gCurNum; 
int gSolCount;
void PrintSolution()
{
	for (int i = 0;i < gN;i++)
	{
		cout << solution[i] << " ";
	}
	cout << endl;
}
void Go()
{
	if (gCurNum == gN)
	{
		gSolCount ++;
		PrintSolution();
		return;
	}

	for (char c = 'a';c < 'a' + gN;c++ )
	{
		if (selected[c] == 0)
		{
			gCurNum++;
			solution[gCurNum - 1] = c;
			selected[c] = 1;
			Go();
			gCurNum --;
			selected[c] = 0;
		}
	}
}
int _tmain(int argc, _TCHAR* argv[])
{

	gN = 9;
	memset(selected,0,sizeof(selected));
	gCurNum = 0;
	gSolCount = 0;
	Go();
	cout << gSolCount << endl;
}
 
还有一个比较巧妙的递归版本
void Swap(char & a,char &b)
{
	char t = a;
	a = b;
	b = t;
}
void Permutation(char * pElement,int N,int startIdx)
{
	if (startIdx == N)
	{
		gSolCount ++;
		//PrintElement(pElement,N);
		return;
	}

	Permutation(pElement,N,startIdx + 1);
	for (int i = startIdx + 1;i < N;i++)
	{
		Swap(pElement[startIdx],pElement[i]);
		Permutation(pElement,N,startIdx + 1);
		Swap(pElement[startIdx],pElement[i]);
	}
}
void TestPermutation()
{
	gN = 9;
	gSolCount = 0;
	char elements[26];
	for (int i = 0;i<gN;i++)
	{
		elements[i] = 'a' + i;
	}

	Permutation(elements,gN,0);
	cout << gSolCount << endl;
}

posted on 2011-06-04 18:26  speedmancs  阅读(249)  评论(0编辑  收藏  举报

导航