【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;
}

转载于:https://www.cnblogs.com/speedmancs/archive/2011/06/04/2072753.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值