Catalan數與出棧順序個數,Java編程類比

來源:互聯網
上載者:User

標籤:ring   static   求和   code   隊列   cat   str   容量   span   

問題描述:

隊列中有從1到7(由小到大排列)的7個整數,問經過一個整數棧後,出棧的所有排列數有多少?
如果整數棧的容量是4(棧最多能容納4個整數),那麼出棧的排列數又是多少?


分析:對於每一個數字i, 在它入棧之前都有 i - 1 個數字通過棧到輸出隊列out(不用考慮這i - 1個數位進出棧順序,因為可以把它們抽象成f(i - 1)), 在它之後又有 n - i個 數字入棧然後出棧(同樣不需要考慮它們的進出棧順序),這樣就得到對每個最後出棧的整數i,它都有f(i - 1)*f(n - i)種出棧順序,求和就是n個數字順序經過棧的出棧順序了。

public class Catalan {    public static int answers = 0;    //請實現go函數    public static void go(Deque from, Deque to, Stack s) {        if(from.size() == 0 && s.empty()) {            answers++;        }        else{            Stack s1 = s.clone();            Stack s2 = s.clone();           // Deque from1 = from.clone();           // Deque from2 = from.clone();            if(from.size() != 0)            {                s1.push(from.getFirst());                from.removeFirst();                go(from, to , s1);                from.addFirst(s1.pop());            }            if(!s2.empty())            {                to.addLast(s2.pop());                go(from, to , s2);            }        }    }    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(from, to, s);        System.out.println(answers);    }}

Catalan數與出棧順序個數,Java編程類比

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.