字符串的排列
原创
©著作权归作者所有:来自51CTO博客作者ReignsDu的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?tpId=13&tqId=11180&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题解:
class Solution {
public:
void dfs(string &str, string &tmp, vector<string> &res, int k, int n) {
if (k == n) {
res.push_back(tmp);
}
else if (k < n) {
for (int i = 0; i < n; i++) {
if (i > 0 && str[i] == str[i - 1]) {
continue;
}
if (str[i] != ' ') {
tmp += str[i];
char ch = str[i];
str[i] = ' ';
dfs(str, tmp, res, k + 1, n);
str[i] = ch;
tmp.pop_back();
}
}
}
}
vector<string> Permutation(string str) {
int n = str.length();
if (n == 0) {
return {};
}
sort(str.begin(), str.end());
vector<string> res;
string tmp;
dfs(str, tmp, res, 0, n);
return res;
}
};