首页 > 代码库 > Catalan数

Catalan数

【问题描述】对于一个栈,已知元素的进栈序列,判断一个由栈中所有元素组成的排列的出栈序列。

有N个数,则代表入栈序列为1,2,3,4,5...,N。求所有可能的出栈序列和总数。

代码如下

#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<stdio.h>
using namespace std;
int N = -1;
int sum = 0;;
//递归算法
//count:当前已经入栈的元素个数
//seq:当前栈
//result:出栈序列,从左到右为出栈序列
void printValidSequence(int count,vector<int> seq,vector<int> result){
    if (count == N){
        result.insert(result.end(), seq.rbegin(), seq.rend());
        for (int i = 0; i < result.size(); ++i){
            cout << result[i];
        }
        cout << endl;
        sum++;
        return;
    }
    vector<int> tmp(seq.begin(), seq.end());
    seq.push_back(++count);    //下一个元素入栈
    printValidSequence(count, seq, result);
    if (!tmp.empty()){         //当前元素出栈出栈
        result.push_back(tmp.back());
        tmp.pop_back();
        printValidSequence(count-1, tmp, result);
    }    
}
//非递归算法
//递归算法
//count:当前已经入栈的元素个数
//seq:当前栈
//result:出栈序列,从左到右为出栈序列
class node{
public:
    vector<int> seq;
    vector<int> result;
    int count;
    node(){
        seq.clear();
        result.clear();
        count = 0;
    }
    void print(){
        result.insert(result.end(), seq.rbegin(), seq.rend());
        for (int i = 0; i < result.size(); ++i){
            cout << result[i];
        }
        cout << endl;
    }
    void add(){
        result.push_back(seq.back());
        seq.pop_back();
    }
    void push(){
        seq.push_back(++count);
    }
};
void printValidSequence(int N){
    vector<node> STACK;
    STACK.push_back(node());
    while (true){
        if (STACK.empty()){
            break;
        }
        node tmp = STACK.back(); //出栈
        node tmp2 = tmp;//入栈(=是拷贝)
        STACK.pop_back();
        if (tmp.count == N){
            tmp.print();
            sum++;
        }
        else{
            if (!tmp.seq.empty()){
                tmp.add();
                STACK.push_back(tmp);
            }
            tmp2.push();
            STACK.push_back(tmp2);
        }
    }
}
int main(){
    cin >> N;
    vector<int> seq;
    vector<int> result;
    printValidSequence(0, seq, result); //递归算法 
    cout << "总数为" << sum << endl;
    sum = 0;
    printValidSequence(N);  //非递归算法
    cout << "总数为" << sum << endl;
    system("pause");
    return 0;
}

也可以用Catalan数求解。

h(n)=h(0)h(n-1)+h(1)h(n-2)+...+h(n-1)h(0)

Catalan数