来自:http://bbs.youkuaiyun.com/topics/350118968
字符串的排列。
题目:输入一个字 符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则输出由字符a、b、c所能排列出来的所有字符串abc、acb、bac、bca、cab和cba。
分析:这是一道很好的考查对递归理解的编程题,
因此在过去一年中频繁出现在各大公司的面试、笔试题中。
--------------------------------------------------
这题确实有点难度,虽然知道用递归,就是递归不出。。
关键通过交换词的顺序,来使得其重新排列。。
下面是一个常用的算法
/**
* by author@ylf
* using template
* permutation
*/
#include <iostream>
using namespace std;
template<class T>
void Permutation(T *arr, int n, int idx);
template<class T>
void Print(T *arr, int n);
template<class T>
void Swap(T* arr, int i, int j);
int main() {
int n;
cin>>n;
char* arr = new char[n];
int i = 0;
for(i=0;i<n;i++)
cin>>arr[i];
Permutation(arr,n,0);
delete []arr;
return 0;
}
template<class T>
void Permutation(T *arr, int n, int idx){
if(idx >= n){
Print(arr, n);
return;
}
int i = idx;
for(i=idx;i<n;i++){
Swap(arr,i,idx);
Permutation(arr,n,idx+1);
Swap(arr,i,idx);
}
}
template<class T>
void Swap(T* arr, int i, int j){
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
template<class T>
void Print(T *arr, int n){
int i = 0;
for(i=0;i<n;i++)
cout<<arr[i];
cout<<endl;
}
4
abcd
abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc
本文介绍了一种使用递归实现字符串所有可能排列的方法。通过交换字符位置达到全排列的效果,并提供了完整的C++代码示例,包括主函数输入处理、排列算法核心逻辑及输出展示。
1万+

被折叠的 条评论
为什么被折叠?



