出栈序列与卡特兰数
2016-08-19 20:34
155 查看
给定一个入栈序列,求出所有可能的出栈序列
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
stack<int> stackOut, stackIn;
vector<vector<int>> res;
int n;
int total = 0;
vector<int> vec;
void out()
{
sort(res.begin(), res.end());
for (auto v : res)
{
for (int i = 0; i < n - 1; i++)
cout << v[i] << " ";
cout << v[n - 1] << endl;
}
}
void Solve(int step)
{
int temp;
if (stackOut.size() == 0 && stackIn.size() == 0)
{
res.push_back(vec);
total++;
return;
}
if (stackOut.size() > 0)
{
temp = stackOut.top();
stackOut.pop();
vec[step] = temp;
Solve(step + 1);
stackOut.push(temp);
}
if (stackIn.size() > 0)
{
temp = stackIn.top();
stackOut.push(temp);
stackIn.pop();
Solve(step);
stackIn.push(temp);
stackOut.pop();
}
}
int main()
{
while (cin >> n)
{
vector<int> v(n);
for (int i = n - 1; i >= 0; --i)
cin >> v[i];
for (int num : v)
stackIn.push(num);
vec.resize(n);
Solve(0);
out();
}
return 0;
}
total的结果是一个卡特兰数
关于卡特兰数有许多应用场景,网上也有许多资料。
leetcode上也有一道关于卡特兰数应用的题:
https://leetcode.com/problems/generate-parentheses/
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
stack<int> stackOut, stackIn;
vector<vector<int>> res;
int n;
int total = 0;
vector<int> vec;
void out()
{
sort(res.begin(), res.end());
for (auto v : res)
{
for (int i = 0; i < n - 1; i++)
cout << v[i] << " ";
cout << v[n - 1] << endl;
}
}
void Solve(int step)
{
int temp;
if (stackOut.size() == 0 && stackIn.size() == 0)
{
res.push_back(vec);
total++;
return;
}
if (stackOut.size() > 0)
{
temp = stackOut.top();
stackOut.pop();
vec[step] = temp;
Solve(step + 1);
stackOut.push(temp);
}
if (stackIn.size() > 0)
{
temp = stackIn.top();
stackOut.push(temp);
stackIn.pop();
Solve(step);
stackIn.push(temp);
stackOut.pop();
}
}
int main()
{
while (cin >> n)
{
vector<int> v(n);
for (int i = n - 1; i >= 0; --i)
cin >> v[i];
for (int num : v)
stackIn.push(num);
vec.resize(n);
Solve(0);
out();
}
return 0;
}
total的结果是一个卡特兰数
关于卡特兰数有许多应用场景,网上也有许多资料。
leetcode上也有一道关于卡特兰数应用的题:
https://leetcode.com/problems/generate-parentheses/
相关文章推荐
- 合理的出栈序列, 卡特兰数, 栈:先进后出
- n个元素进栈,输出所有出栈序列-卡特兰数-递归
- 卡特兰数---n 个元素顺序入栈,则可能的出栈序列有多少种
- 卡特兰数(Catalan)应用:输出所有N对合法括号序列和输出所有已知进栈序列的合法出栈序列
- 用卡特兰数求解对于给定序列有多少种出栈情况
- 入出栈序列的种数—递归及卡特兰数(Catalan)实现
- 卡特兰数(出栈序列以及已知先序遍历求树的形状的个数)
- 出栈序列问题,求卡特兰数
- Bailian4077 出栈序列统计【卡特兰数】(vijos P1122)
- 卡特兰数问题——一个栈(无穷大)的进栈序列为1,2,3,…,n,有多少个不同的出栈序列?
- 一个栈(无穷大)的进栈序列为1,2,3,..n,有多少个不同的出栈序列? (卡特兰数)
- hdu 1023 Train Problem II(卡特兰数的应用)出栈序列的统计
- 3334 数据结构实验之栈与队列七:出栈序列判定
- 数据结构实验之栈与队列七:出栈序列判定
- 栈——判断栈的入出栈序列是否合法
- 栈 出栈序列
- 词典序法生成出栈序列
- amazon 出栈 进栈 序列 题目
- 【回溯法】出栈序列统计
- 剑指offer-合法的出栈序列