import java.util.Arrays; public class N个数的出栈方式 { static int flag_count=0; public static void main(String[] args){ int N=10; int[] array=new int[N]; for(int i=0;i<array.length;i++){ array[i]=i+1; } // countOfoutOfStack(0,0,0,array.length); // System.out.println(flag_count); outOfStack(0,0,0,new int[N],new int[N],array); } public static void outOfStack(int cur,int curIn,int curOut,int[] inStack_,int[] outStack_,int[] array){ //在递归中,如果数组中的元素一直增加,没有覆盖,用一个static数组就可以了 //如果有元素的删除,要用拷贝,太浪费空间了。。还没想出好方法 int[] inStack=Arrays.copyOf(inStack_,inStack_.length); int[] outStack=Arrays.copyOf(outStack_,outStack_.length); // int[] inStack=inStack_; // int[] outStack=outStack_; if(curOut==array.length){ System.out.print("第"+(++flag_count)+"种: "); for(int a:outStack){ System.out.print(a+" "); } System.out.println(); return; } if(curIn>0){ outStack[curOut]=inStack[curIn-1]; outOfStack(cur,curIn-1,curOut+1,inStack,outStack,array); } if (cur<array.length) { inStack[curIn] = array[cur]; outOfStack(cur + 1, curIn + 1, curOut, inStack, outStack, array); } } //只计算出栈方式数,不记录路径的话 public static void countOfoutOfStack(int cur,int curIn,int curOut,int n){ if(curOut==n){ flag_count++; return; } if(curIn>0){ countOfoutOfStack(cur,curIn-1,curOut+1,n); } if (cur<n) { countOfoutOfStack(cur + 1, curIn + 1, curOut, n); } } }