Push solution

In Hikvision's interview, the other party asked such a question:

There is a stack with a large enough capacity, and n elements are pushed into the stack in a certain order. How many kinds of popping sequences are there?

For example, if there are two elements of AB, the order of stacking is AB, and there are two cases of popping:

(1) Into A, out of A, in to B, out of B, the order of popping is AB;

(2) Enter A, enter B, exit B, exit A, and the order of popping is BA.

So with 2 elements, the result is 2.

Analysis: Let f(n) be "the number of types of n elements that are pushed into the stack in a certain order and popped out of the stack". Obviously f(1)=1, f(2)=2. We now analyze the general case. In general, we can use "the first element pushed onto the stack, its position in the stacking sequence" as a classification method.

For example, let's assume that the elements pushed onto the stack are A, B, C, D. We classify the discussion according to the "position of A in the pop-up sequence":

(1) When A is the first to pop out of the stack, A goes first, and then pops out of the stack immediately. In this case, there are a total of "number of types of BCD stacking order" schemes. That is f(n-1).

(2) When A pops out of the stack for the second time, A goes first, B goes in again, and then B needs to come out immediately (so as to ensure that A ranks second) . At this time, there are f(n-2) schemes in total.

(3) When A is popped out of the stack for the third time, A is advanced, and then just make sure that the elements two after A are out before A. At this time, there are f(2)*f(1) schemes in total. f(2) refers to "the number of types in the order of pushing and popping of BC", and f(1) means "the number of types of D's pushing and popping from the stack".

……

Analysis here, the law is very obvious.


Starting from the first item, it is the number of cases where the first pushed element is popped out of the stack at the i+1th.

In the above formula, let f(0)=1.

This is actually the Catalan number (Catalan number, also known as Catalan number).

If implemented by programming, a one-dimensional array needs to be maintained, and the time complexity is O(n^2). (The time complexity of recursive implementation is too high).

The general formula for the Catalan number is h(n)=C(2n,n)-C(2n,n+1)(n=0,1,2,...).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325544403&siteId=291194637