压入栈的操作。
递归的终止情况为push=pop=lenth
坑爹的是每一个i和o后面都有空格,最后一个也有。交的时候老Presentation error...找了半天,才知道。
能压入的就不断的压入,不能压了就开始弹。
AC代码:
#include<stdio.h>
#include<string.h>
#define Max 100
char goal_str[Max];
char source_str[Max];
char stack[Max];
int path[Max];
int lenth,top,pointer;
void print_path(void){
int i;
for(i=0;i<2*lenth;i++){
if(path[i]==1)
printf("i ");
else
printf("o ");
}
printf("\n");
}
void dfs(int npush,int npop){
char tmp;
if(npush==lenth&&npop==lenth){
print_path();
return ;
}
if(npush<lenth){
path[pointer++]=1;
stack[top++]=source_str[npush];
dfs(npush+1,npop);
top--;
pointer--;
}
if(top>0&&stack[top-1]==goal_str[npop]){
tmp=stack[top-1];
path[pointer++]=-1;
top--;
dfs(npush,npop+1);
pointer--;
top++;
stack[top-1]=tmp;
}
}
int main()
{
int n1;
while(scanf("%s%s",source_str,goal_str)!=EOF){
pointer=0;
top=0;
printf("[\n");
lenth=strlen(source_str);
n1=strlen(goal_str);
if(n1==lenth)
dfs(0,0);
printf("]\n");
}
return 0;
}