题解 | #字符串的排列#

字符串的排列

http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7

https://www.bilibili.com/video/BV1nC4y1W7ah?p=2

```function Permutation(str)
{
    // write code here
    //考点:深度遍历优先DFS及回溯
    let arr=str.split('') //先将str转换成数组
    let res=[]
    function swap(p,q){
        [arr[p],arr[q]]=[arr[q],arr[p]] //ES6解构,交换两个元素
    }
    function dfs(p,q){
    if(p===q){res.push(arr.join(''));return}  //如果只剩一个字符,不用交换,将该排列推入res
    for(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(new Set(res)) //利用Set去重
    return res
}
module.exports = {
    Permutation : Permutation
};
全部评论
字符串的排列 u r the first
点赞 回复 分享
发布于 2021-11-23 23:20

相关推荐

代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
06-19 19:06
门头沟学院 Java
码农索隆:别去东软,真学不到东西,真事
点赞 评论 收藏
分享
评论
6
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务