首页 > 其他分享 >全排列

全排列

时间:2023-01-28 23:24:13浏览次数:31  
标签:排列 const backTrack res nums return path

/**
 * 回溯算法
 */
const fullPermutationByFor = (nums = [1,2,3]) => {
    const res = []
    const backTrack = (path) => {
        if(path.length === nums.length){
            res.push(path)
            return path
        }
        for(let i = 0; i < nums.length; i++){
            const item = nums[i]
            if(path.includes(item)) {
                continue
            }
            backTrack(path.concat(item))
        }
    }
    backTrack([])
    return res
}

const fullPermutationByForEach = (nums = [1,2,3]) => {
    const res = []
    const backTrack = (path) => {
        if(path.length === nums.length){
            res.push(path)
            return path
        }
        nums.forEach(num => {
            if(path.includes(num)) {
                // forEach无法跳出循环 api机制 此处逻辑代表不执行下面代码
                return
            }
            backTrack(path.concat(num))
        })
    }
    backTrack([])
    return res
}

  

标签:排列,const,backTrack,res,nums,return,path
From: https://www.cnblogs.com/zhenjianyu/p/17071493.html

相关文章

  • 定位的div环形圆形排列
    要实现一个类似于下图的效果,十个标签从中间随机出现的动画效果,若没有十个则按定义位置出现1.将十个标签都固定在中心位置,通过class,并且动态生成标签颜色<div......
  • 递归(一)003:全排列
    003:全排列总时间限制:1000ms内存限制:65536kB描述给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。我们假设对于小写字母有'a'<'b'<...<......
  • golang字典生成算法实现(全排列实现)
    packagemain//@Title main.go//@Description 入口文件//@Author xiao//@Update noneimport( "flag" "fmt" "log")//字典常量const( lowerCaseChar......
  • 没有重复数字的全排列-js
    题目描述全排列,传入数字输出所有可能出现的情况思路分析经典回溯法例题采用闭包的方式记录总的结果(可以访问外部变量),记录每一层的结果,记录当前的深度,用记事本记录元......
  • 字符串全排列-js
    题目描述思路分析对于全排列类型的题我们都可以按照之前的思路去做,(全排列)。采用回溯的方法。这里的字符串我们也可以借助之前的函数,将字符串转为数组即可代码参考co......
  • 深度优先搜索dfs解决排列问题
    八皇后问题#include<iostream>#include<vector>#include<math.h>usingnamespacestd;intN;vector<int>res;voiddfs(intn){if(n==N)//一种情况结束输出......
  • 递归求字符全排列
    #include<iostream>#include<algorithm>#include<cstring>usingnamespacestd;constintN=10;charn[N];charpath[N];boolused[N];voiddfs(intu){i......
  • 图神经网络 —— 排列不变函数
    简单的排列不变函数:定义:参数的输入顺序不会影响输出的值,如果f(a......
  • 【补档】15 Jan 084. 含有重复元素集合的全排列
    15Jan084.含有重复元素集合的全排列给定一个可包含重复数字的整数集合nums,按任意顺序返回它所有不重复的全排列。输入:nums=[1,1,2]输出:[[1,1,2],[1,2,1],[......
  • 代码随想录算法训练营第二十九天 | * 491.递增子序列 * 46.全排列 * 47.全排列 II
    *491.递增子序列*46.全排列*47.全排列II详细布置491.递增子序列https://programmercarl.com/0491.%E9%80%92%E5%A2%9E%E5%AD%90%E5%BA%8F%E5%88%97.html视频......