原题链接:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/
vector<string> res;
vector<string> permutation(string s) {
dfs(0, s);
return res;
}
void dfs(int x, string s) {
if (x == s.size() - 1) {
res.push_back(s);
return ;
}
set<char> st;
for (int i = x; i < s.size(); i++) {
if (st.count(s[i])) continue;
st.insert(s[i]);
swap(s[i], s[x]);//固定i
dfs(x + 1, s);
swap(s[i], s[x]);//还原
}
}
var resMap = make(map[string]int)
func permutation(s string) []string {
visited := make([]bool, len(s))
dfs(s, "", visited)
resSlice := make([]string, 0,len(s))
for r := range resMap {
resSlice = append(resSlice, r)
}
return resSlice
}
func dfs(s string, str string,visited []bool) {
if len(s) == len(str) {
resMap[str] = 1
return
}
for i, v := range s {
if visited[i] {
continue
}
visited[i] = true
dfs(s, str + string(v), visited)
visited[i] = false
}
}