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

问题

  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//仅此行比问题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);
    }
}

你可能感兴趣的:(java)