题解 | #火车进站#
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); let count = 1 let n, data rl.on('line', function (line) { if (count == 1) { n = Number(line.trim()) } else { data = line.trim().split(' ') } count++ }); rl.on('close', function () { let res = [] let dfs = (toIn, toOut, seq) => { if (toOut.length == 0 && toIn.length == 0) { res.push(seq.join('')) return } // 1.不进,直接出 let train = toOut.pop() if (train) { seq.push(train) // 然后接着遍历 dfs(toIn.slice(), toOut.slice(), seq.slice()) toOut.push(train) // 上一步的还原 seq.pop() } // 2. 不出站,进 train = toIn.shift() if (train) { toOut.push(train) // 然后接着遍历 dfs(toIn.slice(), toOut.slice(), seq.slice()) } } dfs(data, [], []) res.sort() res.forEach(item => console.log(item.split('').join(' '))) })
维护栈