题解 | #字符串的排列#

字符串的排列

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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param str string字符串 
 * @return string字符串一维数组
 */
function Permutation(str) {
    // write code here
    let res = []
    if (str.length === 0) return []
    if (str.length === 1) return [str]
    //发现case:"aa"不通过,加去重
    if (str.length === 2) return [...new Set([str[0] + str[1], str[1] + str[0]])]
    for (let i = 0; i < str.length; i++) {
        let curStr = str[i]
        let rest = str.slice(0, i) + str.slice(i + 1, str.length)
        let restRes = Permutation(rest)
        for (let j = 0; j < restRes.length; j++) {
            res.push(curStr + restRes[j])
        }
    }
    //同理
    return [...new Set(res)]
}
module.exports = {
    Permutation : Permutation
};

全部评论

相关推荐

牛客963010790号:一般是hr拿着老板账号在招人不是真是老板招
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务