zoukankan      html  css  js  c++  java
  • N个数依次进栈,求所有可能的出栈方式

    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);
    		}
    	}
    }
    

      

  • 相关阅读:
    《代码大全》阅读心得一
    vi列模式
    以指定的概率/机会获取元素
    自用VIM配置
    优雅的Javascript
    关于遮罩层
    CSS3属性BorderRadius详解[圆角]
    CSS3属性boxshadow详解[盒子阴影]
    CSS3文字特效
    Css3 Animation详解
  • 原文地址:https://www.cnblogs.com/frostbelt/p/2180788.html
Copyright © 2011-2022 走看看