输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
限制:
1 <= s 的长度 <= 8
class Solution {
private:
vector<string> res;
public:
vector<string> permutation(string s) {
perm(s, 0);
return res;
}
void perm(string& s, int idx) {
if (idx == s.length())
{
res.push_back(s);
return;
}
set<char> visited;
for (int i = idx; i < s.length(); ++i)
{
if (visited.count(s[i]))
continue;
visited.insert(s[i]);
swap(s[i], s[idx]);
perm(s, idx + 1);
swap(s[i], s[idx]);
}
}
};