1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
#include <string>
#include <cstring>
#include <stdio.h>
void permute( const std::string & str );
void permute( const std::string & str, int low, int high );
void swap( std::string & str, int index1, int index2 );
int main()
{
permute( "abcd" );
return 0;
}
void permute( const std::string & str )
{
permute( str, 0, str.length() - 1 );
}
void permute( const std::string & str, int low, int high )
{
/*if low is equal to (high - 2), that means base case
* is reached and the program will swap the third to last
* element with the second to last element (i.e. "abcd" to "acbd")
* and subsequently the third to last element with
* the last element (i.e. "abcd" to "adcb").
* After each swap, there will be a second swap between the second to
* last element and the last element (i.e. "abcd" to "abdc").
* The program will print out the element after every single swap*/
if( low == (high - 2) )
{
for( unsigned int i = low; i <= high; i++ )
{
std::string tempStr = str;
const char* charStr = tempStr.c_str();
if( i == low )
{
printf("%s ", charStr );
swap( tempStr, low + 1, low + 2 );
printf("%s ", charStr );
}
else
{
swap( tempStr, low, i );
printf("%s ", charStr );
swap( tempStr, low + 1, low + 2 );
printf("%s ", charStr );
}
}
}
/*if base case is not reached, then that means that nothing will be
* printed out. Instead, low will be iterated and the initial string
* entered as a parameter will then be used to recursively call
* the permute function again. The recursion stack will the end at the
* base case. When going back up the stack, however, the element at low
* will be swapped with every element after it and then THAT value will
* be entered in to a recursive loop until the base case is again reached
* (i.e. if low is at index location "1" then "abcde" will be entered
* in to the recursive loop, then "acbde", then "adcbe", then "aecdb").
*/
else
{
for( unsigned int i = low; i < high - low; i++ )
{
std::string tempStr = str;
if( i == low )
{
int currentLowValue = low++;
permute( tempStr, currentLowValue, high );
}
else
{
swap( tempStr, low, i );
permute( tempStr, low, high );
}
}
}
}
void swap( std::string & str, int index1, int index2 )
{
char tempVar = str[index1];
str[index1] = str[index2];
str[index2] = tempVar;
}
| |