题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 结果请按字母顺序输出。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
#include <stdlib.h>
#include <string>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
class Solution {
private:
vector<string> vec;
public:
vector<string> Permutation(string str) {
if(str.empty())
{
return vec;
}
/* 调用perm函数进行全排列 */
perm(str,0,str.size());
sort(vec.begin(),vec.end());
return vec;
}
void perm(string str, int i , int n)
{
int j = 0;
if(i == n)
{
vec.push_back(str);
}
else
{
for(j = i; j < n; j++)
{
/* 防止重复的交换 */
if(i != j && str[i] == str[j])
{
continue;
}
swap(str[i],str[j]);
perm(str,i+1,n);
swap(str[i],str[j]);
}
}
}
};
int main(void)
{
string str("abc");
Solution s;
vector<string> v;
int i = 0;
v = s.Permutation(str);
for(i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
return 0;
}