//问题:给定字符串S,生成该字符串的全排列。
//方法1:依次从字符串中取出一个字符作为最终排列
//的第一个字符,对剩余字符组成的字符串生成全排列,
//最终结果为取出的字符和剩余子串全排列的组合。
//?
#include <iostream>
#include <string>
using namespace std;
void permute1(string prefix, string str)
{
if(str.length() == 0)
cout << prefix << endl;
else
{
for(int i = 0; i < str.length(); i++)
permute1(prefix+str[i], str.substr(0,i)+str.substr(i+1,str.length()));
}
}
void permute1(string s)
{
permute1("",s);
}
void permute_my(char* strleft,char* strright);
int main()
{
//method1, unable to remove duplicate permutations.
cout << "method1" << endl;
string str("ABC");
cout<<str.length()<< endl;
//permute1("ABA");
permute1("",str);
/////////////////////
printf("================\n");
permute_my("","ABC");
return 0;
}
//优点:该方法易于理解,但无法移除重复的排列,
//如:s="ABA",会生成两个“AAB”。
void swap(char& a,char& b)
{
char tmp=a;
a=b;
b=tmp;
}
void permute_my(char* strleft,char* strright)
{
int leftlen=strlen(strleft);
int rightlen=strlen(strright);
if(rightlen==0)
cout <<strleft<< endl;
else
{
char buff[256];
//strcpy(buff,strleft);
for(int m=0;m<leftlen;m++)
buff[m]=strleft[m];
for(int i = 0; i < rightlen; i++)
//permute1(prefix+str[i], str.substr(0,i)+str.substr(i+1,str.length()));
{
buff[leftlen]=strright[i];
buff[leftlen+1]='\0';
char buff_right[256];
for(int j=0,k=0;j<rightlen;j++)
{
if(j==i)continue;
buff_right[k++]=strright[j];
}
buff_right[k]='\0';
permute_my(buff,buff_right);
}
}
}
字符串的全排列
最新推荐文章于 2023-01-31 16:02:43 发布