一、题目
二、思路
1、使用dfs的方法
2、利用set去重,每次改变都是只改变不重复的
3、只改变S,当到最后一个时,添加到容器
三、代码
class Solution {
public:
vector<string> permutation(string S) {
vector<string>OutPut;
if(S.empty())
{
return OutPut;
}
//传入字符串,输出数组,第几个
dfs(S,OutPut,0);
return OutPut;
}
void dfs(string S,vector<string>&OutPut,int first)
{
if(first==S.size())
{
OutPut.emplace_back(S);
return;
}
//创建set容器去重
unordered_set<char>res;
for(int i=first;i<S.size();++i)
{
//如果set中没有,就添加递归
if(find(res.begin(),res.end(),S[i])==res.end())
{
res.emplace(S[i]);
//交换的目的:first+1都是相同的,把第i个放到first位置来
swap(S[first],S[i]);
dfs(S,OutPut,first+1);
swap(S[first],S[i]);
}
}
}
};