输出进栈出栈的所有序列

来源:互联网 发布:淘宝图片怎么签 编辑:程序博客网 时间:2024/04/29 19:03

 输出进栈出栈的所有序列

 

/* 输出进栈出栈的所有序列 * 如 abc 则输出可以为:cba,bac,bca,abc,acb * input 为输入字符串,output为输出字符串,保存出栈的序列,需要O(n)的空间复杂度 * stack<char> *s 为模拟的栈 * 思路:递归与回溯*/

 

#include<iostream>#include<stack>using namespace std;
int n=0;void stackseq2(char *input,int in_index, stack<char> *s, char *output,int out_index) {if((in_index==n) && s->empty()) {output[n]=0;cout<<output<<endl;}else {if(in_index<n) {s->push(input[in_index++]);stackseq2(input,in_index, s, output,out_index);in_index--;s->pop();}if(!s->empty()) {output[out_index++]=s->top();s->pop();    stackseq2(input,in_index, s, output,out_index);s->push(output[--out_index]);}}}void main(){stack<char> s;char input[100];cin>>input;while(input[0]!='#'){cout<<"============="<<endl;n=strlen(input);char *output=new char[n+1];stackseq2(input,0, &s, output,0);    delete []output;    cin>>input;}}


 

 

原创粉丝点击