/*
copyright@nciaebupt 转载请注明出处
题目:输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。
分析:这是个递归求解的问题。递归算法有四个特性:(1)必须有可达到的终止条件,否则程序将陷入死循环;(2)子问题在规模上比原问题小;(3)子问题可通过再次递归调用求解;(4)子问题的解应能组合成整个问题的解。
对于字符串的排列问题。如果能生成
n-1个元素的全排列,就能生成n个元素的全排列。对于只有1个元素的集合,可以直接生成全排列。全排列的递归终止条件很明确,只有1个元素时。
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
void exchange(char * str, int i, int j){
if(str == NULL){
return;
}
char tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
void fullPermutationsOfString(char * str, int begin, int end){
if(str == NULL || begin > end){
return ;
}
if(begin == end -1){
std::cout<<str<<std::endl;
}
else{
for(int i = begin; i < end; ++i){
exchange(str, begin, i);
fullPermutationsOfString(str, begin+1, end);
exchange(str, begin, i);
}
}
}
int main(int argc, char ** argv){
char str[] = "abc";
int len = strlen(str);
std::cout<<len<<std::endl;
fullPermutationsOfString(str, 0, len);
system("pause");
return 0;
}
输入一个字符串,打印出该字符串中字符的所有排列。
最新推荐文章于 2023-05-17 19:21:07 发布