题目描述
栈是常用的一种数据结构,有n令元素在栈顶端一侧等待进栈,栈顶端另一侧是出栈序列。你已经知道栈的操作有两•种:push和pop,前者是将一个元素进栈,后者是将栈顶元素弹出。现在要使用这两种操作,由一个操作序列可以得到一系列的输出序列。请你编程求出对于给定的n,计算并输出由操作数序列1,2,…,n,经过一系列操作可能得到的输出序列总数。
输入
一个整数n(1<=n<=15)
输出
一个整数,即可能输出序列的总数目。
样例输入 Copy
3
样例输出 Copy
5
思路:模拟栈操作。这里一开始有n次push和pop的机会。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int cnt = 0, n;
void stk(int ppush, int ppop){
if(ppush == n+1 || ppop == n+1)return;
if(ppush == n && ppop == n){//pop和push次数都用完了
cnt++;
return;
}
if(ppush <= n){//push次数还没用完
stk(ppush + 1, ppop);
}
if(ppop <= ppush){//要现有push才有pop,所以pop一直小于等于push
stk(ppush, ppop + 1);
}
}
int main(int argc, char** argv) {
while(cin >> n){
cnt = 0;
int ppush = 1, ppop = 1;
stk(ppush, ppop);
cout << cnt << endl;
}
return 0;
}