题解 | #火车进站II#

火车进站

http://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109

// 多行输入
const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
const inputArr = [];//存放输入的数据
rl.on('line', function (line) {
    //line是输入的每一行,为字符串格式
    inputArr.push(line.split(' ').map(item => Number(item)));//将输入流保存到inputArr中(用map将字符串数组转为数字)
}).on('close', function () {
   let res = fun(inputArr)//调用函数
   res.forEach(item => console.log(item.join(' '))) //打印结果
})

//解决函数
function fun(arr) {
    let N = arr[0][0];
    let train = arr[1].concat();    //未进站的火车
    let res = [];    //输出的结果
    let station = []    //站台栈内的火车
    let outStation = []    //发出的火车
    let backtrace = (train, station, outStation) => {
        if (outStation.length == N) {
            res.push([...outStation])
            return;
        }
        if (station.length == 0 && train.length != 0) {
            // 如果车站为空且未进站的火车不为空,则进站
            station.push(train.shift())
            backtrace(train, station, outStation)
        } else if (station.length != 0 && train.length == 0) {
            // 如果车站不为空,且没有未进站的火车,则顺序出站
            outStation.push(station.pop())
            backtrace(train, station, outStation)
        } else if (station.length != 0 && train.length != 0) {
            // 如果车站不为空,且还有未进站的火车,则可以选择1.出站,2.进站,并回溯
            let temp1 = [...outStation];
            let temp2 = [...station];
            let temp3 = [...train]
            // 出站
            outStation.push(station.pop())
            backtrace(train, station, outStation)
            // 回溯 
            outStation = temp1;
            station = temp2;
            train = temp3;
            // 进站
            station.push(train.shift())
            backtrace(train, station, outStation)
        }
    }
    backtrace(train, station, outStation)
    return res.sort((a, b) => a.join('') - b.join(''))
}

全部评论

相关推荐

昨天 10:17
门头沟学院 Java
昨天面美团,jvm,juc问的好深啊,感觉小林coding不太够喔,牛油们有没有什么推荐的八股网站嘛🕒 岗位/面试时间👥 面试题目🤔 面试感受
明天不下雨了:小林Coding:https://xiaolincoding.com/ 全栈哥:https://www.pdai.tech/ Guide哥:https://javaguide.cn/ 秀哥:https://interviewguide.cn/ 沉默王二:https://javabetter.cn/home.html 磊哥:https://www.javacn.site/interview/basic/ 小傅哥:https://bugstack.cn/ 源码哥:https://doocs.github.io/source-code-hunter/#/ 各大厂的公众号技术文章和一些经典的书籍
面试太紧张了怎么办?
点赞 评论 收藏
分享
代码飞升:别这样贬低自己,降低预期,放平心态,跟昨天的自己比。做好自己,反而会效率更高心态更好,加油兄弟
点赞 评论 收藏
分享
评论
3
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务