深度优先搜索 回溯:
c++
class Solution {
public:
vector<string> permutation(string s) {
if(s.size()==0){
return {};
}
string temp="";
sort(s.begin(),s.end());
vector<bool>used(s.size());
backtrack(s,temp,used,res);
return res;
}
private:
vector<string> res;
void backtrack(string s,string& path,vector<bool>& used, vector<string>& res)
{
if(path.size()==s.size()){
res.push_back(path);
return;
}
for(int i=0;i<s.size();i++){
if(!used[i]){
if(i>=1&&s[i-1]==s[i]&&!used[i-1])
continue;
path.push_back(s[i]);
used[i]=true;
backtrack(s,path,used,res);
used[i]=false;
path.pop_back();
}
}
}
};
c++需要每次path.pop_back();删除排好的路径,回头
python不需要
class Solution {
public:
vector<string> permutation(string s) {
if(s.size()==0)
return{};
unordered_set<string> res;
vector<int> used(s.size());
string path="";
backtrack(s,path,used,res);
vector<string> ret;
for(auto e:res){
ret.push_back(e);
}
return ret;
}
void backtrack(string s, string& path,vector<int>& used, unordered_set<string>& res){
if(path.size()==s.size() and !res.count(path)){
res.insert(path);
return;
}
for(int i=0;i<s.size();i++){
if(used[i]){
continue;
}
used[i] = 1;
path.push_back(s[i]);
backtrack(s,path,used,res);
used[i] = 0;
path.pop_back();
}
}
};
python
class Solution:
def permutation(self, s: str) -> List[str]:
res = []
used = [False] * len(s)
def dfs(path):
if len(path) == len(s) and path not in res:
res.append(path)
return
for i in range(len(s)):
if used[i]:
continue
used[i] = True
dfs(path+s[i])
used[i] = False
dfs('')
return res