AcWing 842. 排列数字 (递归+非递归) (JavaScript)
原题链接
简单
作者:
gaobowen
,
2019-11-27 19:16:17
,
所有人可见
,
阅读 897
1. 深度搜索递归
let n = 3;
let usedNums = new Int32Array(10);//一个元素只能用一次
let output = [];
//深度搜索
let dfs = x => {
if (x > 0) output.push(x);
if (output.length === n) console.log(output.join(' '));
usedNums[x]++;//已使用标记
for (let i = 1; i <= n; i++)
if (!usedNums[i]) dfs(i);//递归
usedNums[x]--;//回溯
output.pop(x);
}
let buf = '';
process.stdin.on('readable', function () {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputNums = line => line.split(' ').filter(s => s !== '').map(x => parseInt(x));
let getInputStr = line => line.split(' ').filter(s => s !== '');
process.stdin.on('end', function () {
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx === 0) {
let a = getInputNums(line);
n = a[0];
dfs(0);
//loop(n);
}
});
});
2. 深搜的非递归版本
let loop = n => {
let usedNums = new Int32Array(10);//一个元素只能用一次
let stack = [0]; //存储已使用的节点
//存储每一层即将使用的分支, 从1开始
let deepUnused = new Array(n + 1).fill(1);
while (stack.length > 0) {
let deep = stack.length;
let branch = deepUnused[deep];
//先确定出口,当前分支枚举完,回溯
if(deepUnused[deep] > n || stack.length > n){
deepUnused[deep] = 1;
usedNums[stack.pop()]--;
continue;
}
while (branch <= n) {
if (!usedNums[branch]) { // 找到一条分支后,进入下一层
usedNums[branch]++;
stack.push(branch);
deepUnused[deep] = ++branch;
break;
}
deepUnused[deep] = ++branch;
}
//到达终点
if(stack.length > n) console.log(stack.slice(1).join(' '));
}
}