catalan数,c++实现入栈出栈顺序图
#include <iostream> #include<algorithm> #include<stack> #include<vector> using namespace std; bool nixu(vector<int>cp) { for (size_t i = 2; i < cp.size(); ++i) { int max = cp[i - 1]; size_t j = i; while (j < cp.size()) { if (cp[j++] > max)return false; } } return true; } auto delete_zero(vector<int>cp) { for (size_t i = 0; i < cp.size(); ++i) { if (cp[i] == 0) { cp.erase(cp.begin() + i); i--; } /*for (auto j : cp) cout << j << ends; cout << endl;*/ }return cp; } bool set(vector<int>cp) { int first = *(cp.begin()); for (size_t i = 1; i < cp.size(); ++i) if (cp[i] > first)cp[i] = 0; cp=delete_zero(cp); /*for (auto j : cp) cout << j << ends; cout << endl;*/ return nixu(cp); } int main() { int kibou=0; vector<int>num{ 1,2,3,4,5,6,7 }; for (auto i : num) cout << i << ends; cout << endl; s: while (next_permutation(num.begin(), num.begin() + num.size())) { vector<int>newnum = num; for (auto i = newnum.size(); i > 2; --i) { if (!set(newnum)) goto s; else newnum.erase(newnum.begin()); } kibou++; for (auto i : num) cout << i << ends; cout << endl; } cout <<"出栈顺序数"<<++kibou << endl; }
令h(0)=1,h(1)=1,卡塔兰数满足递归式:
h(n)= h(0)*h(n-1) + h(1)*h(n-2) + ... + h(n-1)h(0) (其中n>=2),这是n阶递推关系;
还可以化简为1阶递推关系: 如h(n)=(4n-2)/(n+1)*h(n-1)(n>1) h(0)=1
该递推关系的解为:h(n)=C(2n,n)/(n+1)=P(2n,n)/(n+1)!=(2n)!/(n!*(n+1)!) (n=1,2,3,...)
卡塔兰数列的前几项为(sequence A 0 0 0 1 0 8 in OEIS) [注: n = 0, 1, 2, 3, … n]
1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640, 343059613650, 1289904147324, 4861946401452, …
所望隔山海