火车进站

给定一个正整数N代表火车数量,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号,火车站只有一个方向进出,同时停靠在火车站的列车中,只有后进站的出站了,先进站的才能出站。要求输出所有火车出站的方案,以字典序排序输出。

进阶:时间复杂度: O(n!) ,空间复杂度: O(n)

输入描述:

第一行输入一个正整数N(0 < N < 10),第二行包括N个正整数,范围为1到10。

输出描述:

输出以字典序从小到大排序的火车出站序列号,每个编号以空格隔开,每个输出序列换行,具体见sample。

示例1

输入
3
1 2 3
输出
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1

说明

第一种方案:1进、1出、2进、2出、3进、3出
第二种方案:1进、1出、2进、3进、3出、2出
第三种方案:1进、2进、2出、1出、3进、3出
第四种方案:1进、2进、2出、3进、3出、1出
第五种方案:1进、2进、3进、3出、2出、1出
请注意,[3,1,2]这个序列是不可能实现的。

Java 编程

package cn.net.javapub.demo2.demo;

/**
 * @author: shiyuwang
 */

import java.util.*;

public class Main {
    static Stack<String> stack = new Stack<String>();
    static Stack<String> list = new Stack<String>();
    static List<String> result = new ArrayList<>();

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            in.nextLine();

            String line = in.nextLine();
            process(line);
        }
    }

    public static void process(String s) {
        String[] strs = s.split("\\s");
        for (int i = strs.length - 1; i >= 0; i--) {
            list.push(strs[i]);
        }
        method("");
        Collections.sort(result);
        for (String r : result) {
            System.out.println(r);
        }
    }

    public static void method(String s) {
        if (stack.empty() && list.empty()) {
            result.add(s.trim());
            return;
        }
        if (!stack.empty()) {
            String str = stack.pop();
            method(s + " " + str);
            stack.push(str);
        }
        if (!list.empty()) {
            String str = list.pop();
            stack.push(str);
            method(s);
            stack.pop();
            list.push(str);
        }
    }
}

展示效果:

华为OD机试 - 火车进站 (Java 2024 E卷 100分)_Java