无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。
示例1:
输入:S = "qwe" 输出:["qwe", "qew", "wqe", "weq", "ewq", "eqw"]
示例2:
输入:S = "ab" 输出:["ab", "ba"]
代码如下:
//递归--回溯
class Solution {
public:
void dfs(vector<string>& res,string& S,int i)
{
if(i==S.size())
{
res.push_back(S);
}
else
{
//注意j从i开始,因为原排列也是一种排列
for(int j=i;j<S.size();j++)
{
swap(S[i],S[j]);//交换字母
dfs(res,S,i+1);
swap(S[i],S[j]);//还原
}
}
}
vector<string> permutation(string S) {
vector<string> res;
dfs(res,S,0);
return res;
}
};