const res =[], temp =[]const len = str.length
const arr = str.split('')varhelp=function(){if(temp.length === len){
res.push(temp.join(''))return}for(const s of arr){
temp.push(arr.shift())help()
arr.push(temp.pop())}}help()return[...(newSet(res))]
方法二
letset=newSet()letaddstr=(pre, str)=>{if(str.length ==0){set.add(pre)}for(let i =0; i < str.length; i++){addstr(pre + str[i], str.slice(0, i).concat(str.slice(i+1)));}}addstr("", str)return Array.from(set)
方法三
let arr=str.split('')//先将str转换成数组let res=[]functionswap(p,q){[arr[p],arr[q]]=[arr[q],arr[p]]//ES6解构,交换两个元素}functiondfs(p,q){if(p===q){res.push(arr.join(''));return}//如果只剩一个字符,不用交换,将该排列推入resfor(let i=p;i<=q;i++){//先自己跟自己交换,下一轮跟索引号+1交换,一直到和最后一个元素交换swap(p,i)dfs(p+1,q)//深度遍历swap(p,i)//回溯}}dfs(0,arr.length-1)
res=Array.from(newSet(res))//利用Set去重return res
方法4
let len = str.length
let arr = str.split('')let path =[], res =[], used =[]let death
constdfs=(path, used, arr, death, len)=>{if(death === len){
res.push([...path].join(''))return}for(let i =0; i < len; i++){if(!used[i]){
path.push(arr[i])
used[i]=truedfs(path, used, arr, death +1, len)
used[i]=false
path.pop()}}}dfs(path, used, arr,0, len)return[...(newSet(res))]
方法一 const res = [], temp = [] const len = str.length const arr = str.split('') var help = function() { if (temp.length === len) { res.push(temp.join('')) return } for (const s of arr) { temp.push(arr.shift()) hel