栈
求栈的所有出栈可能
对于这道题要非常注意这道题不是求全排列 比如输入的数据是1,2,3 如果是求全排列其输出的列表为
public static void main ( String[ ] args) {
List< String> list = new ArrayList < > ( ) ;
int [ ] nums = new int [ ] { 1 , 2 , 3 } ;
fun ( list, nums, "" ) ;
Collections. sort ( list) ;
for ( String s : list
) {
System. out. println ( s) ;
}
}
public static void fun ( List< String> list, int [ ] nums, String temp) {
if ( temp. length ( ) == nums. length) {
list. add ( temp) ;
return ;
}
for ( int num : nums) {
if ( ! temp. contains ( String. valueOf ( num) ) ) {
fun ( list, nums, temp + num) ;
}
}
}
package com. demo. Solution;
import java. util. *;
public class Main {
public static void main ( String[ ] args) {
Scanner scan = new Scanner ( System. in) ;
while ( scan. hasNext ( ) ) {
int count = scan. nextInt ( ) ;
int [ ] nums = new int [ count] ;
for ( int i = 0 ; i < count; i++ ) {
nums[ i] = scan. nextInt ( ) ;
}
List< String> list = new ArrayList < > ( ) ;
Stack< Integer> stack = new Stack < > ( ) ;
fun ( list, "" , stack, nums, 0 , 0 ) ;
Collections. sort ( list) ;
for ( String str : list) {
System. out. println ( str) ;
}
}
}
public static void fun ( List< String> list, String str, Stack< Integer> stack, int [ ] nums, int out, int insert) {
if ( out == nums. length) {
list. add ( str. trim ( ) ) ;
return ;
}
if ( insert < nums. length) {
stack. push ( nums[ insert] ) ;
fun ( list, str, stack, nums, out, insert + 1 ) ;
stack. pop ( ) ;
}
if ( ! stack. isEmpty ( ) ) {
int temp = stack. pop ( ) ;
fun ( list, str + " " + temp, stack, nums, out + 1 , insert) ;
stack. push ( temp) ;
}
}
}
这道题在牛客上就有https://www.nowcoder.com/questionTerminal/97ba57c35e9f4749826dc3befaeae109 解题思路就是我们建立一个栈, 统计他的入栈次数和出栈次数, 并且使用字符串记住他的出栈顺序, 在每一次递归里如果入栈次数没到就先入栈, 如果入栈次数到了,就递归出栈, 并且栈中的元素有俩种情况, 一个是出栈了, 一个是留着不出栈, 那我们统计了出栈的情况, 就应该恢复现场再去统计没出栈的情况
判断一个出栈序列是否正确
上面我们讲到了求一个栈的所有出栈可能, 下面我们给一个入栈序列和一个出栈序列判断他是不是合法的
public static void main ( String[ ] args) {
int [ ] insert = new int [ ] { 1 , 2 , 3 , 4 } ;
int [ ] out = new int [ ] { 4 , 3 , 2 , 1 } ;
System. out. println ( is ( insert, out) ) ;
}
private static boolean is ( int [ ] insert, int [ ] out) {
Stack< Integer> stack = new Stack < > ( ) ;
int index = 0 ;
for ( int value : insert) {
stack. push ( value) ;
while ( ! stack. isEmpty ( ) && stack. peek ( ) == out[ index] ) {
stack. pop ( ) ;
index++ ;
}
}
return stack. isEmpty ( ) ;
}
解题思路是我们初始化一个栈, 将入栈序列一次循环入栈, 每入一次就判断此时栈顶的元素是不是在出栈序列中,如果是就出栈, 如果不是就继续入栈, 直到所有的元素入栈完毕, 最后判断一开始初始化的这个栈是不是为空