JavaScript实现回溯算法中的全排列

回溯模板

  • 初始化path值和附加辅助的值
  • 终止递归条件
  • 遍历条件递归
var permute = function(nums) {
    let res = []
    const dfs = (path,...) => {
        if(终止条件) return
        // 需要遍历一遍数组
        nums.forEach(n => {
            if(递归条件) dfs(path.concat(n))
        })
    }
    // 初始化path
    dfs(初始化的path值,...)
    // 返回结果就可以了
    return res
};

不重复元素重全排列

例:[ 1, 2, 3] 得:[[ 1, 2, 3],[ 2, 3, 1],[ 3, 2, 1],[ 1, 3, 2],[ 2, 1 ,3],[ 3, 1, 2]]

var permute = function(nums) {
    let res = []
    const dfs = (path) => {
        if(path.length == nums.length) {
            res.push(path)
            return
        } 
        nums.forEach(n => {
            if(!path.includes(n)) {
                dfs(path.concat(n))
            }
        })
    }
    dfs([])
    return res
};
// 时间复杂度:O(n! * n)
// 空间复杂度:O(n)

重复元素的全排列

例:[ 1, 2, 2] 得:[[ 1, 2, 2],[2 , 1,2],[2 , 2,1]]

function samePermute(nums) {
    let res = []
    const dfs = (path, sameIndex) => {
        if(nums.length == path.length) {
            res.push(path)
            return
        } 
        // control控制相同元素不能继续排列
        // sameIndex相同元素不能作为主分支元素
        let control = []
        for(let i = 0;i < nums.length;i++) {
            if(sameIndex.includes(i) || conrtol.includes(nums[i])) continue
            control.push(nums[i])
            dfs(path.concat(nums[i]),sameIndex.concat(i))
        }
    }
    dfs([],[])
    return res
}

多维数组全排列

例:[[ ‘a’, ‘b’],[ ‘A’,‘B’ ],[ ‘1’,‘2’ ]] 得:[ ‘aA1’,‘aB1’,‘aA2’,‘aB2’,‘bA1’,‘bA2’,‘bB1’,‘bB2’ ]

function pailie (arr) {
    let res = []
    const dfs = (path, index) => {
        if(path.length === arr.length) {
            res.push(path)
            return
        }
        arr[index].forEach(n => {
            dfs(path + n, index + 1);
        })
    }
    dfs("", 0)
    return res
}
// 时间复杂度O(n! * n)
// 空间复杂度O(n)

数字组成的最小数字

例给一个数字30000,给一个数组[2,1,9],实现一个算法,能数组中的数,组成比给定数字小的,最大数29999

下列解法:回溯加剪枝

function ArraytoMin(nums,target){
    let max = 0
    const dfs = (path) => {
        if(parseInt(path) > target) return
        if(path) max = Math.max(max,parseInt(path))
        nums.forEach(n => {
            dfs(path + n)
        })
    }
    return max
}

如果还有全排列的题目后续更新~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

影风莫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值