题目描述为:
输入一个字符串,请输出这个字符串的所有排列.
思路:
可以使用递归的方法,每次选定一个字符固定在首位,然后让其它的字符做全排列.
#include <iostream>
#include <string>
void funcCalcAll(string &str, int from, int to);
int main()
{
string str;
cout << "input a string: " << endl;
cin >> str;
funcCalcAll(str, 0, str.length() - 1);
return 0;
}
void funcCalcAll(string &str, int from, int to)
{
if(to < from)
return ;
if(from == to)
{
for(int i = 0; i <= to; i++)
{
cout << str[i];
}
cout << endl;
}
else
{
for(int j = from; j <= to; j++)
{
swap(str[j], str[from]); //选定当前字符为首字符
funcCalcAll(str, from + 1, to); //将剩余字符全排列
swap(str[j], str[from]); //将字符还原
}
}
}
此方法的时间复杂度为O(n!),还有一种使用字典序排列的方法处理这个问题,但是暂时没有理解.其思路是:
1. 找到当前排列中最后一个升序的首位位置i,其元素为a.
2. 找到排列中第i位右边最后一个比a大的元素b.
3. 交换a、b.
4. 把第i+1位到最后的部分反转.