括号匹配 强大的DFS

轩载 神牛黑水浮云空间

#include<stdio.h>

#include<string.h>

char s[20];

int sum,l;

void work(int k,int cnt)   
/*cnt用来记录到当前k位置为止尚未被匹配的'(''的个数,如果出现负数直接
                        返回,如果到串尾并且
cnt为0那么就是一种合法的状态,sum加1;否则继续DFS。
*/
{

     if(k==l||cnt<0) 

     {if(cnt==0) sum++;}

     else if(s[k]=='?')
     {

        work(k+1,cnt-1);   

        work(k+1,cnt+1);

     }

     else
      {

         if(s[k]=='(') cnt+=2;

         work(k+1,cnt-1);

      }

}

int main()

{

    while(gets(s)){

       l=strlen(s);

       sum=0; 

       work(0,0);

       printf("%d\n",sum);

    }

}

posted on 2011-05-11 10:50  more think, more gains  阅读(189)  评论(0编辑  收藏  举报

导航