数据结构与算法
数学上的递推公式
可以推到得出,过程较为复杂,此处略过
![][1]
[1]: http://latex.codecogs.com/gif.latex?S_n=\sum_{i=0}^{n-1}S_i*S_{n-1-i}
参看:
<a href=”http://baike.baidu.com/link?url=oxX5VdsRLCJBkWTTTyPQFWAOW50V8Wqo6b1uljrgX3MrTO6j_82-wiFW-r-2i9GkuG83dBn3YHiKkEejlhCquq”>卡特兰数</a>
以下代码给出了递推关系:
int countS(int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return 1;
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += countS(i)*countS(n-1-i);
}
return sum;
}
```
## 模拟算法
栈每次有两种情况:入栈和出栈,但是,不是每种组合都是合法的。合法的出栈入栈必须满足以下条件(1表示入栈,0表示出栈):
1. 最终出栈和入栈的次数一样,也就是0和1的数量都等于元素的个数
2. 栈为空时不能有出栈动作,也就是在任意时刻,已经出现的1必须大于等于0出现的次数
例如:
111000(合法)
110001(不合法)
模拟生成合法序列的 C++ 代码如下:
```
#include <iostream>
using namespace std;
int m,a[20] = {1}, count0,count1;
void binSeq(int n) {
//边界条件,输出合法的序列,其中 m 为一半的数组长度。
if (2*m == n) {
for (int i = 0; i < 2*m ; i++) {
cout << a[i];
}
cout << endl;
return;
}
//条件判断,任意时刻1的个数小于 m 且大于0的个数
if (count1 < m && count1 > count0) {
a[n] = 1;
count1++;
binSeq(n+1);
count1--;
a[n] = 0;
count0 ++;
binSeq(n+1);
count0 --;
}
//当不能所有的元素均已进行过入栈动作
else if (count1 == m) {
a[n] = 0;
count0++;
binSeq(n+1);
count0--;
}
//当1和0数量相等即栈为空时,应入栈
else if (count0 == count1) {
a[n] = 1;
count1++;
binSeq(n+1);
count1--;
}
}
int main() {
cin >> m;//输入元素个数
count0 = 0;
count1 = 1;//首先必须入栈
binSeq(1);
return 0;
}
```
最后的代码如下所示:
```
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int Size, PopCount, PushCount;//定义变量
vector < int >operation; // we can use 1 to stand for "push", and 0 for "pop"
stack < int >simulation;
//计算 n 个元素出栈顺序的个数
int countS(int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return 1;
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += countS(i)*countS(n-1-i);
}
return sum;
}
//主要函数,原理与上面的简化班函数相同,不再写详细注释
void binSeq(int n, int *arr)
{
if (2 * Size == n) {
vector < int >::iterator Iter;
int j = 0;
for (Iter = operation.begin(); Iter != operation.end(); Iter++) {
if (1 == (*Iter)) {
simulation.push(arr[j]);
j++;
} else {
cout << simulation.top() << " ";
simulation.pop();
}
}
cout << endl;
return;
}
if (PushCount < Size && PushCount > PopCount) {
operation.push_back(1);
PushCount++;
binSeq(n + 1, arr);
operation.pop_back();
PushCount--;
operation.push_back(0);
PopCount++;
binSeq(n + 1, arr);
operation.pop_back();
PopCount--;
}
else if (PushCount == Size) {
operation.push_back(0);
PopCount++;
binSeq(n + 1, arr);
operation.pop_back();
PopCount--;
}
else if (PopCount == PushCount) {
operation.push_back(1);
PushCount++;
binSeq(n + 1, arr);
operation.pop_back();
PushCount--;
}
}
int main()
{
cout << "Please input the size of sequence:";
operation.push_back(1);
cin >> Size;
cout << "Please input the size of sequence<int>:\n";
int seq[Size];
for (int i = 0; i < Size; i++) {
cin >> seq[i];
}
cout << "The anwser is:\n";
PopCount = 0;
PushCount = 1;
binSeq(1, seq);
cout << "The number of all cases is : " << countS(Size) << endl;
return 0;
}
```