/*
Permutations of a string are defined to be all possible orderings of the characters within the string. For example, the string "cat" has the following permutations:
{ "cat", "cta","atc","act","tca","tac" }
Write an efficient C/C++ function, generate_permutations(), that will generate all the permutations of a given string. This program is expected to be invoked with the input string as the only parameter and expected to output the results to the standard output.
Assumption : If the characters in the string are duplicated, some permutations will be identical, however they are still listed out. For example, "all" will generate the following permutations: { "all","all","lal","lal","lla","lla" }
Function prototype : void generate_permutations(const char* input_string)
Test run : void generate_permutations("eyjafjallajokull").
*/
#include <iostream>
#include <hash_set>
#include <string>
std::hash_set<std::string> strSet;
void swap(char* x, char* y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
};
void permute(char* a, int i, int n)
{
if(i == n)
{
std::string curWord(a);
if(strSet.find(curWord) == strSet.end())
{
strSet.insert(a);
printf("%s\n", a);
}
}
else
{
for(int j = i; j <= n; j++)
{
swap(a + i, a + j);
permute(a, i + 1, n);
swap(a + i, a + j);
}
}
};
int main()
{
char a[] = "caat";
permute(a, 0, 3);
return 0;
}
面试题 06162012 [1]
最新推荐文章于 2024-10-20 17:51:39 发布