题解 | #火车进站#
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void (async function () {
// Write your code here
// 深度优先遍历:终止条件 数据处理递归 数据还原(回溯)
// shift 删除第一个,返回删除元素 (改变原数组)
// unshift 首位增加一个元素 (改变原数组)
// push尾部增加一个元素 (改变原数组)
// pop尾部删除一个元素,返回删除元素(改变原数组
let line1 = await readline()
let line2 = await readline()
let len = Number(line1);
let arr = line2.split(" ").map(Number);
let luxian = [];
// arr所有的车 iList进站 oLIst出站
function run(arr, iList, oLIst) {
if (oLIst.length === len) {
luxian.push(oLIst.join(" "));
return;
}
// 进站
if (arr.length) {
iList.push(arr.shift());
run(arr, iList, oLIst);
arr.unshift(iList.pop()); // 数据还原
}
// 出站
if (iList.length) {
oLIst.push(iList.pop());
run(arr, iList, oLIst);
iList.push(oLIst.pop()); // 数据还原
}
}
run(arr, [], []);
// 输出
luxian.sort().forEach((item) => {
console.log(item);
});
})();
查看10道真题和解析