题目
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
思路
递归思想,参考别人,感谢原作者。原文地址:https://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7
固定第1位:让所有位依次作为第一位;
利用递归,其余位作为一个字符串继续排列,以此类推。
需要注意的是递归结束条件:排列开始位为字符串的最后一位则结束递归;
示例
输入:asdd
输出:
adds
adsd
asdd
dads
dasd
ddas
ddsa
dsad
dsda
sadd
sdad
sdda
代码
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution{
public:
vector<string> Permutation(string str){
vector<string> result;
// 如果字符串为空返回空
if (str.empty())
return result;
Permutation(str,result,0);
// 排字典序
sort(result.begin(),result.end());
return result;
}
private:
void Permutation(string str, vector<string> &result, int begin) {
// 结束递归条件
if (begin == str.size() - 1) {
// 判断字符串组,如果字符串已经存在就不在存储
if (find(result.begin(), result.end(), str) == result.end())
result.push_back(str);
} else {
for (int i = begin; i < str.size(); ++i) {
swap(str[begin], str[i]);
// 固定前面N为,对其余位进行排列
Permutation(str, result, begin + 1);
// 恢复原来位置,便于下一次排序
swap(str[begin], str[i]);
}
}
}
void swap(char &a, char &b){
char temp(a);
a = b;
b = temp;
}
};
int main(){
string input1("asdd");
string input2("cbsd");
Solution re;
vector<string> result1(re.Permutation(input1));
vector<string> result2(re.Permutation(input2));
while (!result1.empty()){
cout << result1.front() << endl;
result1.erase(result1.begin());
}
return 0;
}