您的位置:首页 > 其它

字符全排列的另一种实现

2010-10-18 16:39 211 查看
朋友让我帮忙写一个密钥空间的穷举,我想到了全排列。

到网上查了一下,网上的全排列算法,大部分是基于交换原则,由递归算法来给出答案。

我这里给出另一个算法,是基于乘法原理和数据结构来给出结果。也是采用递归算法。

似乎该方法更容易理解,且很形象。

乘法原理是说,选第一个数有n种可能, 第二个数n-1种可能,第三个数n-2个可能... 第n数1种可能。

则总的可能数为: n * (n-1)(n-2)...*1 = n! 种可能。

说实话,该程序是在递归函数中,隐含的使用了数据交换过程。典型的穷举搜索算法。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
typedef struct{
char c;
char outc;
int flag;
}List;
void initStruct(char *pStr, List *pList);
void permutation(List *pList, int depth);
char *pStr = "12345";
int main(int argc, char *argv[])
{
int len = strlen(pStr);
List* pList=(List *)malloc(len *sizeof(List) );
initStruct(pStr,pList);		//初始化数据结构
permutation(pList,0);
_getch();
return 0;
}
void initStruct(char *pStr, List *pList)
{
for(unsigned int i=0; i<strlen(pStr); i++)
{
pList[i].c=pStr[i];		//初始化结构
pList[i].flag = 1;		//设定元素均为可选状态
}
}
void permutation(List *pList, int depth)
{
int i;
int len =strlen(pStr);
// 当递归处理到最后一个元素,表示已选择完毕,输出结果
if(depth==len)
{
for(i=0; i< len; i++)
{
printf("%c ",pList[i].outc);
}
printf("/n");
return;
}
//遍历所有可被选择的元素
for(i=0; i<len; i++)
{
//当元素还没有被选择时,选定该元素
if(pList[i].flag==1)
{
pList[i].flag=0;				//设定给元素已经选择标志
pList[depth].outc=pList[i].c;	//把该元素送到输出数组中
permutation(pList,depth+1);		//递归到下一个处理元素
pList[i].flag=1;				//恢复元素为初始状态
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: