目录
全排列(回溯算法+深度优先搜索)
要求:给定一个 没有重复 数字的序列,返回其所有可能的全排列。
例如:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
代码:
let permutation = function(nums) {
const res = []; // 储存返回多少种排列法的集合。
const used = {}; // 记录哪个数据用过了
dfs([]);
function dfs(path) {
if (path.length == nums.length) {
res.push(path.slice());
return;
}
for (const num of nums) {
if (used[num]) continue;
path.push(num);
used[num] = true;
dfs(path);
path.pop();
used[num] = false;
}
}
return res;
}
八皇后 (回溯算法+ 深度优先搜索)
要求:8x8的棋盘上,其中每个皇后都不同行、不同列,也不在对角线上。这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。能有多少种摆法
例如:
代码解析:
let allQueen = (n) => {
// 由画图得出规律, 左对角线的点[行+列]都是相等的,右对角线上的点[列-行]都是相等的。
// 所以可以声明左右对角线数据,在同索引的位置进行检测数据来判断是否在一条线上。
// 返回的情况综合, 同列数组, 左侧对角线, 右侧对角线
let res = [], colList=[],leftLine=[],rightLine = [];
let canPut = (row,col) => {
// 如果同列中不存在 && 左对角线不存在 && 有对角线不存在
if (!colList[col] && !leftLine[row+col] && !right[col-row]) {
return true
}
return false
}
let dns = (path, row) => {
if (path.length === n) {
res.push([...path]); // 已达到一种摆放解法。
return
}
for(let col=0;col<n;col++) { // 一行中的第几个位置
if (canPut(row, col)) {
path.push(col);
colList[col] = 1;
leftLine[col+row] = 1;
rightLine[col-row] = 1;
dns(path, row+1);
path.pop();
colList[col] = undefined;
leftLine[col+row] = undefined;
rightLine[col-row] = undefined;
}
}
}
dns([], 0)
return res;
}
allQueen(8)