问题:
给定一个字符串,求出其全排列的个数。为简便起见,假定所给字符串的字符均不同,若有m个字符,
则共n=m!种排列。
解决方案:
#include <iostream>
#include <assert.h>
#include <string.h>
using namespace std;
void swapChar(char *charA,char *charB){
char temp = *charA;
*charA = *charB;
*charB = temp;
}
//k表示当前选取到第几个数,m表示共有多少个数
void Permutation(char* pStr,int k,int m,int &sum)
{
assert(pStr);
if(k == m){
sum++;
}
else
{
for(int i = k; i < m;i++)
{
swapChar((pStr+i),(pStr+k));
Permutation(pStr,k+1 , m,sum);
swapChar((pStr+i),(pStr+k));
}
}
}
int main(void)
{
static int maxLen = 10;
char *str = new char[maxLen];
cout<<"\t指定一个最大长度为"<<maxLen<<"的字符串"<<endl<<"\t";
cin>>str;
cout<<"\t您输入的字符串为: "<<str<<endl;
int len = strlen(str);
if(maxLen < len)
{
cout<<"\t字符串:"<<str<<"的长度超过了"<<maxLen<<endl;
return -1;
}
cout<<"\t字符串:"<<str<<"的全排列:";
int sumOfPermu = 0;
Permutation(str , 0 , strlen(str),sumOfPermu);
cout<<"共 "<<sumOfPermu<<" 个."<<endl;
delete str;
str = NULL;
return 0;
}
结果:
参考:
http://blog.csdn.net/morewindows/article/details/7370155