Problem Description
学弟经过一年的训练了,此时候是该检验他们水平的时候了,记得Carryon讲过栈和字典树,
而且他一开始讲栈的时候就讲了栈的进出方式,不同的出栈方式其实是一个卡特兰数,都过了
一年了,他觉得学弟也应该知道了,所以现在有一个问题,需要求出一个字符串S不同的出栈方
式N,并且把N种不同的出站方式(按照字典序)输出来。(字符串的每个字符互不相同)
Input
输入字符串S;(0<s.length<14)
Output
第一行输出N表示有多少种;
接下来N行输出不同的出栈序列;
Sample Input
abs
Sample Output
5
abs
asb
bas
bsa
sba
代码①:
直接传字符串和栈不用回溯,效率慢一些
注意这里如果用cin的话,即使加了ios::sync_with_stdio(false)也会超时,比c输入输出的慢了4倍左右
一个3000多ms,一个600多ms
#include <iostream>
#include <cstdio>
#include <set>
#include <stack>
#include <cstring>
using namespace std;
set<string> Set;
char s[20];
int len;
void dfs(int pos,string sa,stack<char> sta)
{
if(pos==len)
{
while(!sta.empty())
{
sa+=sta.top();
sta.pop();
}
Set.insert(sa);
return;
}
if(sta.empty())
{
sta.push(s[pos]);
dfs(pos+1,sa,sta);
}
else //非空
{
// 入栈
sta.push(s[pos]);
dfs(pos+1,sa,sta);
sta.pop();
//栈顶出
sa+=sta.top();
sta.pop();
dfs(pos,sa,sta);// pos位不变
}
return ;
}
int main()
{
scanf("%s",s);
len =strlen(s);
string sa="";
stack<char> sta;
while(!sta.empty())
sta.pop();
dfs(0, sa, sta);
//cout<<Set.size()<<endl;
printf("%d\n",Set.size());
while(!Set.empty())
{
//cout<<*Set.begin()<<endl;
printf("%s\n",(*Set.begin()).c_str());
Set.erase(Set.begin());
}
return 0;
}
/*
将所有排列放入set中,set会自动按字典序排列
当队列为空时,将栈内元素全部弹出
当栈为空时,入栈,
当栈非空时,
①栈顶元素出栈
②入栈
*/
代码②:
回溯做法
#include <iostream>
#include <cstdio>
#include <set>
#include <stack>
#include <cstring>
#include <iterator>
using namespace std;
#define ll long long
set<string> Set;
ll catalan[20];
int len;
char str[20];
char st[20]; //栈
char tmp[20]; //表示出栈的元素队列
void init()
{
catalan[0]=1;
for(int i=1;i<14;i++)
for(int j=0;j<i;j++)
catalan[i] += catalan[j] * catalan[i-j-1];
}
void dfs(int pos,int pst, int ptmp)
{
if(pos==len)
{
string tt = "";
for(int i=0;i<ptmp;i++)
tt += tmp[i];
for(int i=pst-1;i>=0 ;i--)
tt +=st[i]; // 将栈中元素也放入tt中
Set.insert(tt);
return ;
}
if(pst==0) // 栈为空,入栈
{
st[pst]=str[pos];
dfs(pos+1,pst+1,ptmp);
}
else //非空
{
// 入栈
st[pst]=str[pos];
dfs(pos+1,pst+1,ptmp);
//栈顶出
char c= st[pst-1];
tmp[ptmp]=st[pst-1];
dfs(pos,pst-1,ptmp+1);// pos位不变
st[pst-1]= c; //回溯---需要注意
}
return ;
}
int main()
{
//卡特兰数博客:https://blog.csdn.net/wookaikaiko/article/details/81105031
// 令h(0)=1,h(1)=1,catalan数满足递推式。h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (n>=2)
init();
while(~scanf("%s", str))
{
len = strlen(str);
Set.clear();
dfs(0, 0, 0);
printf("%lld\n",catalan[len]); //其实这里用Set.size()也行的,慢不了多少
// printf("%lld\n",Set.size());
set<string>::iterator it;
for(it = Set.begin(); it != Set.end(); it++)
printf("%s\n", (*it).c_str() );
}
return 0;
}
/*
将所有排列放入set中,set会自动按字典序排列
当队列为空时,将栈内元素全部弹出
当栈为空时,入栈,
当栈非空时,
①栈顶元素出栈
②入栈
*/