[编程题]: 入栈出栈序列
发布日期:2021-05-06 22:54:27 浏览次数:44 分类:技术文章

本文共 2581 字,大约阅读时间需要 8 分钟。

[编程题]: 入栈出栈序列

题目描述

输入n,入栈序列为[1, 2, …, n]

求所有可能的出栈序列

结题思路

给定包含n个数的入栈序列,出栈序列的可能情况根据卡特兰公式有

种。
对这n个数,得到它们的全排列,每得到一个全排列对其进行判断,看是否能成为一个合法的出栈序列。

示例

n = 4那么入栈序列为 [1, 2, 3, 4]可能的出栈序列为:[1, 2, 3, 4],[1, 2, 4, 3],[1, 3, 2, 4],[1, 3, 4, 2],[1, 4, 3, 2],[2, 1, 3, 4],[2, 1, 4, 3],[2, 3, 1, 4],[2, 3, 4, 1],[2, 4, 3, 1],[3, 2, 1, 4],[3, 2, 4, 1],[3, 4, 2, 1],[4, 3, 2, 1]

共14种。

代码

package demo;import java.util.ArrayList;import java.util.List;import java.util.Scanner;import java.util.Stack;public class Main {
private static List
> res = new ArrayList<>(); public static void main(String[] args) {
Scanner input = new Scanner(System.in); int T = input.nextInt(); for (int times = 0; times < T; times++) {
int n = input.nextInt(); res.clear(); helper(n, 1, new ArrayList<>(), new boolean[n + 1]); int line = 0; for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i)); line++; if (line < 3 && i < res.size() - 1) System.out.print(","); else {
System.out.println(); line = 0; } } } } private static void helper(int n, int index, List
nums, boolean[] visited) {
if (index == n + 1) {
boolean ans = check(n, nums); if (ans) res.add(new ArrayList<>(nums)); return; } else {
for (int i = 1; i <= n; i++) {
if (visited[i]) continue; visited[i] = true; nums.add(i); helper(n, index + 1, nums, visited); nums.remove(nums.size() - 1); visited[i] = false; } } } private static boolean check(int n, List
nums) {
int num1 = 1; int index2 = 0; Stack
stack = new Stack<>(); while (num1 <= n || index2 < n) {
if (num1 == nums.get(index2)) {
num1++; index2++; } else {
if (!stack.isEmpty() && stack.peek() == nums.get(index2)) {
stack.pop(); index2++; } else {
if (num1 > n) return false; // 入栈序列入完栈仍然不能找到相等的情况 stack.push(num1); num1++; } } } if (stack.isEmpty() && num1 == n + 1 && index2 == n) return true; else return false; }}
上一篇:随机规划
下一篇:[编程题]: 整数拆分问题

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年03月28日 19时19分53秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

HTML特效代码大全 2019-03-04
Java爬虫.HttpClient 2019-03-04
网页的基本页面实现 ---- 标签 2019-03-04
Java.数组算法(补充) 2019-03-04
Java.常用类.StringBuffer和StringBuilder 2019-03-04
RDD行动操作算子 --- fold(初始值)、reduce 2019-03-04
【Python数据分析与处理 实训02】 ---2012欧洲杯信息分析(数据过滤与排序) 2019-03-04
【Python数据分析与处理 实训04】--- 探索1960 - 2014美国犯罪数据(时间序列处理应用) 2019-03-04
KeyError: “[‘xxxx‘] not found in axis“ 2019-03-04
【Python数据分析与处理 实训05】--- 探索虚拟姓名数据(数据合并) 2019-03-04
java编程常见类型题 --- 面向对象编程、程序逻辑(金字塔)、多线程同步 2019-03-04
java编程常见类型题 --- 程序逻辑(最小台阶)、多线程(计算读取)、Swing布局(国际棋盘) 2019-03-04
【MapReduce】基础案例 ---- 自定义OutputFormat <根据内容输出到指定文件目录中> 2019-03-04
【Android】 模拟器上运行程序报错 2019-03-04
【sklearn练习】KMeans ---- iris(鸢尾花)数据集聚类评估 2019-03-04
【HTML5 CSS】display和visibility的区别 2019-03-04
java线程(4)——使用多个线程操作同一个对象(买票的例子) 2019-03-04
前端HTML中表单action属性的作用 2019-03-04
java线程(17)——Lock锁,三个线程抢票加上lock锁后变成三个线程排队买票 2019-03-04
java线程(19)——信号灯法,电视播放,生产者与消费者的案例 2019-03-04