我在网上看到了这个问题,我正试图解决它C++
.我有以下算法:
char permutations( const char* word ){
int size = strlen( word );
if( size <= 1 ){
return word;
}
else{
string output = word[ 0 ];
for( int i = 0; i < size; i++ ){
output += permutations( word );
cout << output << endl;
output = word[ i ];
}
}
return "";
}
Run Code Online (Sandbox Code Playgroud)
举例来说,如果我有abc
我的投入,我想显示abc
,acb
,bac
,bca
,cab
,cba
.所以,我想要做的是
'abc' => 'a' + 'bc' => 'a' + 'b' + 'c'
=> 'a' + 'c' + 'b'
Run Code Online (Sandbox Code Playgroud)
所以我需要o word
每个函数调用传递一个较少的char.有人可以帮忙怎么做?
我建议使用algorithm
C++中的头库来做得更容易; 并且作为一个函数可以这样写:
void anagram(string input){
sort(input.begin(), input.end());
do
cout << input << endl;
while(next_permutation(input.begin(), input.end()));
}
Run Code Online (Sandbox Code Playgroud)
但是,既然你想要它没有STL,你可以这样做:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap (char *x, char *y)
{
char ch = *x;
*x = *y;
*y = ch;
};
void permutate_(char* str, size_t index )
{
size_t i = 0;
size_t slen = strlen(str);
char lastChar = 0;
if (index == slen )
{
puts(str);
return;
}
for (i = index; i < slen; i++ )
{
if (lastChar == str[i])
continue;
else
lastChar = str[i];
swap(str+index, str+i);
permutate_(str, index + 1);
swap(str+index, str+i);
}
}
// pretty lame, but effective, comparitor for determining winner
static int cmpch(const void * a, const void * b)
{
return ( *(char*)a - *(char*)b );
}
// loader for real permutor
void permutate(char* str)
{
qsort(str, strlen(str), sizeof(str[0]), cmpch);
permutate_(str, 0);
}
Run Code Online (Sandbox Code Playgroud)
你可以通过发送一个排序的字符数组来调用,
permutate("Hello World");
Run Code Online (Sandbox Code Playgroud)