字符串的全排列问题,感觉有点复杂,后续再继续看看,现在实现的是递归版本,还有很多其他类似的问题可以思考。
string_permutation
eg:
关键字string key=”abc”,
那么对应的全排列是 “abc” “acb” “bac” “bca” “cab” “cba”
典型的子问题的解
下面是代码
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <set>
const int N = 1024;
///////////////
void swap_value(char &val1, char &val2)
{
char tmp = val1;
val1 = val2;
val2 = tmp;
}
void string_permutation(char *key, int from, int to)
{
int i = 0;
if (from == to)
{
for (i = 0; i < strlen(key); i++)
std::cout << key[i];
std::cout << std::endl;
return;
}
for (i = from; i <= to; i++)
{
//这里转换一次以后,还需要转换第二次,将原顺序转换回来
swap_value(key[from], key[i]);
string_permutation(key, from+1, to);
swap_value(key[i], key[from]);
}
}
////////////////////////////
int main(int argc, char *argv[])
{
char line[N] = "abcdef";
std::cout << "key string " << line << std::endl;
int len = strlen(line);
int k = 0;
string_permutation(line, 0, len-1);
//std::cout << "spin string " << line << std::endl;
//int i = 0;
std::cout << std::endl;
return 0;
}