卡特兰数计算,出栈序列可能个数,栈容量有限制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35558510/article/details/81591974

问题

  1. 队列中有从1到7(由小到大排列)的7个整数,问经过一个整数栈后,出栈的所有排列数有多少?
  2. 如果整数栈的容量是4(栈最多能容纳4个整数),那么出栈的排列数又是多少?

问题1代码


public class Catalan {

    public static int answers = 0;
    int maxStackSize = 4; //栈最大容量

    public static void go(int deq, int sta) {
        if(deq>0) {
            go(deq-1, sta+1);
        }
        if(sta>0) {
            go(deq, sta-1);
        }
        if(deq==0&&sta==0) {
            answers++;
        }
    }

    public static void main(String[] args) {
        Deque from = new Deque();
        Deque to = new Deque();
        Stack s = new Stack();
        for(int i=1;i<=7;i++) {
            from.addLast(i);
        }
        go(7, 0);
        System.out.println(answers);
    }
}

问题2代码


public class Catalan {

    public static int answers = 0;
    int maxStackSize = 4;

    public static void go(int deq, int sta) {
        if(deq>0 &&sta<maxStackSize) {  //仅此行比问题1多了一个限制
            go(deq-1, sta+1);
        }
        if(sta>0) {
            go(deq, sta-1);
        }
        if(deq==0&&sta==0) {
            answers++;
        }
    }

    public static void main(String[] args) {
        Deque from = new Deque();
        Deque to = new Deque();
        Stack s = new Stack();
        for(int i=1;i<=7;i++) {
            from.addLast(i);
        }
        go(7, 0);
        System.out.println(answers);
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页