您的位置:首页 > 其它

给定入栈顺序,求解出栈顺序

2015-08-05 10:45 155 查看
#include <iostream>
#include <vector>
using namespace std;
void finn(const int n,int cur,vector<int>&stac,vector<int>&outL,int&count)
{
    if((int)outL.size ()==n)//终点
    {
        //如果需要对应的出栈顺序那么outL中即为所求
        count++;
    }
    if(cur!=n+1)//入栈
    {
        //操作
        stac.push_back(cur);
        //进入下层
        finn(n,cur+1,stac,outL,count);
        //恢复
        stac.pop_back ();
    }
    if(!stac.empty())//出栈
    {
        //留底
        int temp=stac[(int)stac.size ()-1];
        //操作
        outL.push_back (temp);
        stac.pop_back ();
        //进入下层
        finn(n,cur,stac,outL,count);
        //恢复
        outL.pop_back ();
        stac.push_back (temp);
    }
}
int f(const int n)
{
    vector<int> stac;
    vector<int> outL;
    int count=0;
    finn(n,1,stac,outL,count);
    return count;
}
main()
{
    int n;
    cout<<"n=";
    cin>>n;
    cout<<"共"<<f(n)<<"个"<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: