Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4972912
  • 博文数量: 1696
  • 博客积分: 10870
  • 博客等级: 上将
  • 技术积分: 18357
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-30 15:16
文章分类
文章存档

2017年(1)

2016年(1)

2015年(1)

2013年(1)

2012年(43)

2011年(17)

2010年(828)

2009年(568)

2008年(185)

2007年(51)

分类: C/C++

2010-08-05 12:44:50

Question: Print all the permutations of a string. Write code in C.

Answer: Here is a recursive solution to print all the permutations of a string. However, this solution does not take care of duplicates. It is assumed that there are no duplicates in the string. I left out the implementation of the swap method since that implementation is not important here.

The idea is to keep the first character constant and generate permutations with the rest. Then keep the first two characters constant and generate permutations with the rest until you are out of characters :)

void permutate( char[] str, int index )
{
int i = 0;
if( index == strlen(str) )
{ // We have a permutation so print it
printf(str);
return;
}
for( i = index; i < strlen(str); i++ )
{
swap( str[index], str[i] ); // It doesn't matter how you swap.
permutate( str, index + 1 );
swap( str[index], str[i] );
}
}
permutate( "abcdefgh", 0 );

Now what do we do if there are duplicates in the string? The trick is to sort the characters in the alphabetical order first. We can then ignore the duplicates easily when generate the permutation.

void permutate( char[] str, int index )
{
int i = 0;
static lastChar = 0;
if( index == strlen(str) )
{ // We have a permutation so print it
printf(str);
return;
}
for( i = index; i < strlen(str); i++ )
{
if( lastChar == str[i] ) {
continue;
} else {
lastChar = str[i];
}
swap( str[index], str[i] ); // It doesn't matter how you swap.
permutate( str, index + 1 );
swap( str[index], str[i] );
}
}
permutate( sort("Hello World"), 0 );

Simple right? Any comments or suggestions are always welcome.

Like this post? Please Digg it or Stumble it.
阅读(790) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~