Estructura de datos y análisis de algoritmos: descripción del lenguaje C ++
Escriba dos rutinas con las siguientes declaraciones:
void permute (String str);
void permute (char [] str, int low, int high); La
primera rutina es un controlador, llama a la segunda rutina y Muestra todas las permutaciones de caracteres en String str.
Por ejemplo, si str es "abc", la cadena de salida es abc, acb, bac, bca, cab, cba y la segunda rutina usa la recursividad.
#include<iostream>
#include<string>
using namespace std;
void permute(string &str);
void permute(string &str,int low,int high);
void swap(string &str,int a,int b);
bool isswap(string &str,int a,int b);
int main()
{
string str="abc";
permute(str);
}
void swap(string &str,int a,int b)
{
if(str[a]==str[b])
return ;
char c=str[a];
str[a]=str[b];
str[b]=c;
}
void permute(string &str)
{
permute(str,0,str.length());
}
void permute(string &str,int low,int high)
{
if(high-low==1)
{
string s;
for(int i=0;i<high;i++)
{
s+=str[i];
}
cout<<s<<endl;
}
for(int i=low;i<high;i++)
{
swap(str,low,i);
permute(str,low+1,high);
swap(str,low,i);
}
}
En las dos rutinas del libro, const se usa antes que str. Cuando lo escribí yo mismo, descubrí que si se agregaba const, la llamada a la función swap sería incorrecta. Así que eliminé la const.
Visto desde otros lugares existe la posibilidad de duplicación
Deduplicación + entrada
#include<iostream>
#include<string>
using namespace std;
void permute(string &str);
void permute(string &str,int low,int high);
void swap(string &str,int a,int b);
bool isswap(string &str,int a,int b);
int main()
{
string str;
cin>>str;
permute(str);
}
void swap(string &str,int a,int b)
{
if(str[a]==str[b])
return ;
char c=str[a];
str[a]=str[b];
str[b]=c;
}
bool isswap(string &str,int a,int b)
{
for(int i=a;i<b;i++)
if(str[i]==str[b])
return false;
return true;
}
void permute(string &str)
{
permute(str,0,str.length());
}
void permute(string &str,int low,int high)
{
if(high-low==1)
{
string s;
for(int i=0;i<high;i++)
{
s+=str[i];
}
cout<<s<<endl;
}
for(int i=low;i<high;i++)
{
if(isswap(str,low,i))
{
swap(str,low,i);
permute(str,low+1,high);
swap(str,low,i);
}
}
}
Por favor avise.