就是之前全排列的再研究版:
#include <stdio.h>
#include <string.h>
char res[100]="";
void Exchange(char* pStr,int i,int j)
{
char temp = pStr[i];
pStr[i] = pStr[j];
pStr[j] = temp;
}
bool IsSubStr(char* pStr, char test)
{
if (pStr == nullptr)
{
return false;
}
char* temp = pStr;
while (*temp != '\0')
{
if (*temp++ == test)
{
return true;
}
}
return false;
}
void DoPermute(char* pStr, int k, char* pre, char* suf)
{
int len1 = 0;
if (pre != nullptr)
{
len1 = strlen(pre);
}
int len2 = 0;
if (suf != nullptr)
{
len2 = strlen(suf);
}
int len = strlen(pStr);
if (k == len-len1-len2)
{
strncat_s(res,pre,len1);
strncat_s(res,pStr,k);
strncat_s(res,suf,len2);
printf("%s \n", res);
}
else
{
for (int i=k; i < len; ++i)
{
memset(res,0,100);
if (IsSubStr(pre,pStr[i]) || IsSubStr(suf,pStr[i]))
{
continue;
}
Exchange(pStr,i,k);
DoPermute(pStr,k+1,pre,suf);
Exchange(pStr,i,k);
}
}
}
void RecursivePermute(char* pStr)
{
DoPermute(pStr,0,"a",nullptr);
}
int main()
{
char temp[] = "abcde";
RecursivePermute(temp);
}
很神奇吧,哈哈