Catalan number and stack order number, Java programming simulation

Source: Internet
Author: User

Problem Description:

There are 7 integers in the queue from 1 to 7 (from small to large), what is the number of all permutations of the stack after an integer stack?
If the capacity of the integer stack is 4 (the stack can hold up to 4 integers), what is the number of permutations of the stack?


Analysis: For each number I, before it goes into the stack there are i-1 numbers through the stack to the output queue out (do not consider the I-1 numbers in and out of the stack order, because they can be abstracted into F (i-1)), after which there are n-i numbers into the stack and then out of the stack (also do not need to consider their entry and exit ), so that you get the integer i for each last stack, which has an F (i-1) *f (n-i) of the stack order, and the sum is N number order through the stack order.

 Public classCatalan { Public Static intAnswers = 0; //Please implement the Go function     Public Static voidGo (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 voidMain (string[] args) {Deque from=NewDeque (); Deque to=NewDeque (); Stack s=NewStack ();  for(inti=1;i<=7;i++) {from.addlast (i);        } go (from, to, s);    System.out.println (answers); }}

Catalan number and stack order number, Java programming simulation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.