Java机试题*:火车进站(queue队列FIFO-stack栈FILO-deque双向队列/ 动态规划、递归)
描述
给定一个正整数N代表火车数量,0进阶:时间复杂度:O(n!)\O(n!) ,空间复杂度:O(n)\O(n)
输入描述:
有多组测试用例,每一组第一行输入一个正整数N(0
输出描述:
输出以字典序从小到大排序的火车出站序列号,每个编号以空格隔开,每个输出序列换行,具体见sample。
这里指的按字典序,是各种出站情况的,按编号大小输出
import java.util.*; // 队列表示未进站的火车。先进先出 // 栈表示已进站的火车。先进后出 // 每次火车进站后有两种选择:1.直接出站 2.等待下列火车进站 使用递归考虑 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int n = sc.nextInt(); // 未进站的火车 Queuequeue = new LinkedList<>(); // 已进站的火车 Stack stack = new Stack<>(); for (int i = 0; i < n; i++) { queue.offer(sc.nextInt()); } // 存储,每种进出情况,出站顺序 List outQueueList = new ArrayList<>(); // 获取所有出站队列保存到outQueueList processOutQueue(queue, stack, "", outQueueList); // 排序 Collections.sort(outQueueList); for (String str : outQueueList) { System.out.println(str); } } } private static void processOutQueue(Queue queue, Stack stack, String outQueue, List outQueueList) { // 如果队列和栈都为空,表示火车已全部进出完成。则保存出站信息 if (queue.isEmpty() && stack.isEmpty()) { outQueueList.add(outQueue.trim()); return; } // 队列和栈有两种情况:出栈或进栈 // 一:出栈,已进站的需要更新出站信息outQueue if (!stack.isEmpty()) { // 先克隆 Queue tempQueue = new LinkedList<>(queue); Stack tempStack = (Stack ) stack.clone(); String tempOutQueue = outQueue + (tempStack.pop() + " "); processOutQueue(tempQueue, tempStack, tempOutQueue, outQueueList); } // 二:队列进栈:没进站的继续进站 if (!queue.isEmpty()) { // 先克隆 Queue tempQueue = new LinkedList<>(queue); Stack tempStack = (Stack ) stack.clone(); tempStack.push(tempQueue.poll()); processOutQueue(tempQueue, tempStack, outQueue, outQueueList); } } }
题目来源:牛客网
参考链接:
参考链接:https://www.nowcoder.com/questionTerminal/97ba57c35e9f4749826dc3befaeae109