回溯模板
- 初始化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
}
如果还有全排列的题目后续更新~~~