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