/** * 回溯算法 */ 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