描述
输入一个长度为 n 字符串,打印出该字符串中字符的所有排列,你可以以任意顺序返回这个字符串数组。例如输入字符串ABC,则输出由字符A,B,C所能排列出来的所有字符串ABC,ACB,BAC,BCA,CBA和CAB。
数据范围:n<10
要求:空间复杂度 O(n!),时间复杂度 O(n!)
输入描述:输入一个字符串,长度不超过10,字符只包括大小写字母。
示例1
输入:“ab”
返回值:[“ab”,“ba”]
说明:返回[“ba”,“ab”]也是正确的
示例2
输入:“aab”
返回值:[“aab”,“aba”,“baa”]
示例3
输入:“abc”
返回值:[“abc”,“acb”,“bac”,“bca”,“cab”,“cba”]
示例4
输入:“”
返回值:[]
代码
class Solution {
public:
vector<string> Permutation(string str) {
vector<string> str1;
sort(str.begin(),str.end());
do{
str1.push_back(str);
}while(next_permutation(str.begin(), str.end()));
return str1;
}
};
如:
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
string str = "adse";
vector<string> temp;
sort(str.begin(), str.end());
do {
temp.push_back(str);
} while (next_permutation(str.begin(), str.end()));
for (int i = 0; i < temp.size(); i++) {
cout << temp[i] << endl;
}
return 0;
}