算法:火车进站

描述

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

要求输出所有火车出站的方案,以字典序排序输出。

数据范围: 1≤n≤10 

进阶:时间复杂度: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]这个序列是不可能实现的。 

 

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            int[] array = new int[a];
            for (int i=0; i<a; i++) {
                array[i]=in.nextInt();
            }
            Stack<Integer> stack = new Stack<Integer>();
            Set<String> set = new TreeSet<>();
            getRes(array, a, 0, stack, set, "");
            for (String tmp : set) {
                System.out.println(tmp);
            }
        }
    }

    public static void getRes(int[] array, int size, int index, Stack<Integer> stack, Set<String> set, String order) {
        if (index >= size) {
            while (!stack.isEmpty()) {
                order = order+stack.pop()+" ";
            }
            set.add(order);
            return ;
        }
        if (!stack.isEmpty()) {
            Stack<Integer> stackW = copy(stack);
            stack.add(array[index]);

            int tmpIndex = 1;
            String tmpOrder = order;

            getRes(array, size, index+1, stack, set, order);

            while (!stackW.isEmpty()) {
                tmpIndex++;
                tmpOrder = tmpOrder+stackW.pop()+" ";
                Stack<Integer> stackVal = copy(stackW);
                stackVal.add(array[index]);
                getRes(array, size, index+1, stackVal, set, tmpOrder);
            }
        }
        else {
            stack.add(array[index]);
            getRes(array, size, index+1, stack, set, order);
        }
    }

    public static Stack<Integer> copy(Stack<Integer> stack) {
        Stack<Integer> res = new Stack<Integer>();
        Object[] objs = stack.toArray();
        for(Object tmp : objs) {
            res.add((int)tmp);
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值