原题链接:Leecode 剑指 Offer 38. 字符串的排列
DFS
class Solution {
public:
vector<string> res;
vector<bool> v;
void dfs(const string& s,int n,int l,string& t)
{
if(l==n)
{
res.push_back(t);
return ;
}
for(int i=0;i<n;i++)
{
if(v[i] || (i>0 && s[i-1]==s[i] && !v[i-1]))
continue;
v[i]=true;
t+=s[i];
dfs(s,n,l+1,t);
t.pop_back();
v[i]=false;
}
}
vector<string> permutation(string s) {
sort(s.begin(),s.end());
int n=s.size();
v.resize(n);
string t;
dfs(s,n,0,t);
return res;
}
};
参考此题Leecode 31. 下一个排列 全排列的解法(当然,直接用库函数next_permutation
也行):
class Solution {
public:
bool next_Permutation(string& s)
{
int n=s.size();
int i=n-2,j=n-1,k=n-1;
while(i>=0 && s[i]>=s[j])
{
i--;j--;
}
if(i<0) return false;
while(s[i]>=s[k]) k--;
swap(s[i],s[k]);
sort(s.begin()+j,s.end());
return true;
}
vector<string> permutation(string s) {
sort(s.begin(),s.end());
vector<string> res;
do
{
res.push_back(s);
}while(next_Permutation(s));
return res;
}
};