题解 | #火车进站#已画图,用树形结构进行多分支穷举
火车进站
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 while(line = await readline()){ let trainNum = Number(line) let inSequence = await readline() inSequence = inSequence.split(' ').map(item=>Number(item)) let stackOut = [] let stackIn = [] let res = [] countSequence(stackOut,stackIn,inSequence,res) res.sort(function(a,b){ return Number(a)-Number(b) }) res = new Set([...res]) res= [...res] res.forEach((item=>console.log(item.split('').join(' ')))) function countSequence(stackOut,stackIn,inSequence,res){ if(inSequence.length==0){ while(stackIn.length!=0){ stackOut.push(stackIn.pop()) } res.push(stackOut.map(item=>Number(item)).join('')) return } stackIn.push(inSequence.shift()) countSequence([...stackOut],[...stackIn],[...inSequence],res) while(stackIn.length!=0){ stackOut.push(stackIn.pop()) countSequence([...stackOut],[...stackIn],[...inSequence],res) } } } }()