题解 | #火车进站#

火车进站

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

题目链接

火车进站

题目描述

一共有 辆火车需要入站,编号为 。火车站的进出共享一个轨道,这意味着后入站的火车需要先出站,这符合的“后进先出” (LIFO) 特性。

现在,已经知道了火车的入站顺序,你需要计算所有不同的出站顺序,并按照字典序从小到大依次输出。

解题思路

这是一个经典的全排列问题,其核心是模拟火车进站和出站的所有可能性。由于火车站的轨道遵循“后进先出”的原则,我们可以把它抽象成一个栈。

在任何时刻,我们都面临两种选择:

  1. 进站 (Push): 如果还有未进站的火车,我们可以让下一辆火车进入车站(入栈)。
  2. 出站 (Pop): 如果车站(栈)内有火车,我们可以让栈顶的火车出站,并将其记录到出站序列中。

为了穷举所有由这两种操作组成的合法序列,我们可以使用深度优先搜索 (DFS)回溯法

我们可以定义一个递归函数 dfs 来探索所有可能的选择路径。这个函数的状态可以由“下一辆待进站的火车索引”、“当前站内的火车(栈)”以及“当前已生成的出站序列”来描述。

  • 递归基 (Base Case): 当我们生成的出站序列长度等于火车总数 时,说明我们找到了一个完整的、合法的出站序列。我们将此序列存入结果列表中,并结束当前递归分支。

  • 递归步骤 (Recursive Step): 在当前状态下,我们尝试所有可行的操作:

    • 尝试“出站”: 如果栈不为空,我们就弹出一辆火车,将其加入到当前出站序列,然后继续进行下一步的递归搜索。搜索返回后,我们需要进行回溯——即将这辆火车从出站序列中移除,并重新压回栈中,以恢复到之前的状态,从而探索其他可能性。
    • 尝试“进站”: 如果还有未进站的火车,我们就将下一辆火车压入栈中,然后继续递归搜索。同样,在搜索返回后,我们也需要回溯,将这辆火车从栈中弹出。

当整个搜索过程结束后,我们就得到了所有可能的出站序列。最后,根据题目要求,对所有序列进行字典序排序再输出。

代码

#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

int n;
vector<int> in_order;
vector<vector<int>> all_sequences;

// in_idx: 下一辆要进站的火车在 in_order 中的索引
// station: 当前在站台(栈)中的火车
// current_out: 当前已出站的火车序列
void dfs(int in_idx, stack<int>& station, vector<int>& current_out) {
    // 基线条件:当出站序列满了,说明找到一个完整解
    if (current_out.size() == n) {
        all_sequences.push_back(current_out);
        return;
    }

    // 选择1:出站(如果栈不为空)
    if (!station.empty()) {
        int train_out = station.top();
        station.pop();
        current_out.push_back(train_out);

        dfs(in_idx, station, current_out);

        // 回溯
        current_out.pop_back();
        station.push(train_out);
    }

    // 选择2:进站(如果还有待进站的火车)
    if (in_idx < n) {
        int train_in = in_order[in_idx];
        station.push(train_in);

        dfs(in_idx + 1, station, current_out);

        // 回溯
        station.pop();
    }
}

int main() {
    cin >> n;
    in_order.resize(n);
    for (int i = 0; i < n; ++i) {
        cin >> in_order[i];
    }

    stack<int> station;
    vector<int> current_out;
    dfs(0, station, current_out);

    sort(all_sequences.begin(), all_sequences.end());

    for (const auto& seq : all_sequences) {
        for (int i = 0; i < seq.size(); ++i) {
            cout << seq[i] << (i == seq.size() - 1 ? "" : " ");
        }
        cout << endl;
    }

    return 0;
}
import java.util.*;

public class Main {
    static int n;
    static int[] in_order;
    static List<List<Integer>> all_sequences = new ArrayList<>();

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        in_order = new int[n];
        for (int i = 0; i < n; i++) {
            in_order[i] = sc.nextInt();
        }

        dfs(0, new Stack<Integer>(), new ArrayList<Integer>());

        // 对结果进行字典序排序
        Collections.sort(all_sequences, (list1, list2) -> {
            for (int i = 0; i < n; i++) {
                if (!list1.get(i).equals(list2.get(i))) {
                    return list1.get(i) - list2.get(i);
                }
            }
            return 0;
        });

        for (List<Integer> seq : all_sequences) {
            for (int i = 0; i < seq.size(); i++) {
                System.out.print(seq.get(i) + (i == seq.size() - 1 ? "" : " "));
            }
            System.out.println();
        }
    }

    static void dfs(int in_idx, Stack<Integer> station, List<Integer> current_out) {
        if (current_out.size() == n) {
            all_sequences.add(new ArrayList<>(current_out));
            return;
        }

        // 选择1:出站
        if (!station.isEmpty()) {
            int train_out = station.pop();
            current_out.add(train_out);
            dfs(in_idx, station, current_out);
            // 回溯
            current_out.remove(current_out.size() - 1);
            station.push(train_out);
        }

        // 选择2:进站
        if (in_idx < n) {
            int train_in = in_order[in_idx];
            station.push(train_in);
            dfs(in_idx + 1, station, current_out);
            // 回溯
            station.pop();
        }
    }
}
import sys

n = 0
in_order = []
all_sequences = []

# in_idx: 下一辆待进站火车的索引
# station: 栈
# current_out: 当前出站序列
def dfs(in_idx, station, current_out):
    if len(current_out) == n:
        all_sequences.append(list(current_out))
        return

    # 选择1:出站
    if station:
        train_out = station.pop()
        current_out.append(train_out)
        dfs(in_idx, station, current_out)
        # 回溯
        current_out.pop()
        station.append(train_out)

    # 选择2:进站
    if in_idx < n:
        train_in = in_order[in_idx]
        station.append(train_in)
        dfs(in_idx + 1, station, current_out)
        # 回溯
        station.pop()

def main():
    global n, in_order
    lines = sys.stdin.readlines()
    n = int(lines[0])
    in_order = list(map(int, lines[1].split()))
    
    dfs(0, [], [])
    
    all_sequences.sort()
    
    for seq in all_sequences:
        print(*seq)

if __name__ == "__main__":
    main()

算法及复杂度

  • 算法:回溯法 / 深度优先搜索 (DFS)
  • 时间复杂度:问题的解的数量是第 卡特兰数 。生成每个解需要进行 次入栈和 次出栈,共 步。因此生成所有解的时间复杂度与 相关。最后对 个长度为 的序列进行排序,时间复杂度为 。总时间复杂度由这两部分构成。
  • 空间复杂度:主要由存储所有 个结果序列所消耗,每个序列长度为 ,因此空间复杂度为 。递归的深度最大为 ,所以栈空间为
全部评论

相关推荐

a了2.5,应该能进面了吧
投递科大讯飞等公司10个岗位
点赞 评论 收藏
分享
07-23 15:05
门头沟学院 Java
熊大不大:不好意思KPI数据刚刚刷新,刚刚达标
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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