8.1 Question E: [Introduction to Recursion] Statistics of Pop Sequences

Title description

The stack is a commonly used data structure. There is n to make the element wait on the top side of the stack to be pushed into the stack, and the other side of the top of the stack is the pop sequence. You already know that there are two types of stack operations: push and pop. The former is to push an element onto the stack, and the latter is to pop the top element of the stack. Now to use these two operations, a series of output sequences can be obtained from one operation sequence. Please program to find for a given n, calculate and output the total number of output sequences that may be obtained from the operand sequence 1, 2, ..., n, after a series of operations.
 

enter

An integer n (1<=n<=15) 

Output

An integer, the total number of possible output sequences.

Sample input Copy

3

Sample output Copy

5

prompt

First understand the two basic operations of the stack. Push to the stack is to put elements on the top of the stack, move the pointer on the top of the stack one bit up, and wait for the queue to be moved up one bit. Pop pop is to pop the top element of the stack and stack The top pointer moves down one place. 
Use a process to simulate the process of entering and exiting the stack, and backtracking can be achieved by looping and recursion: repeat this process, if it can be pushed into the stack, then an element is entered, if it can be popped, then an element is out. Just try one by one, and count once when the number of popped elements reaches n (this is also the condition for the end of the recursive call). 

#include <iostream>
#include <cstdio>
using namespace std;
int n,ans;
void dfs(int in,int out)
{
    if(out==0) ans++;
    else if(in==0){
        dfs(in+1,out-1);//进栈
    }
    else{
        dfs(in+1,out-1);//进栈
        dfs(in-1,out);//出栈
    }
 
}
int main()
{
    while(scanf("%d",&n)!=EOF){
        ans=0;
        dfs(0,n);
        printf("%d\n",ans);
    }
    return 0;
}

 

Guess you like

Origin blog.csdn.net/wangws_sb/article/details/114931159