现在的位置: 首页 > 综合 > 正文

福州大学 括号问题

2012年07月12日 ⁄ 综合 ⁄ 共 413字 ⁄ 字号 评论关闭

这题当时比赛的时候想到是深搜,但当时深搜做得不多,没做得出,后来看以大牛代码才会写,主要是判断条件写得好。

#include<stdio.h>
#include<string.h>
char str[20];
int l,cnt;
void DFS( int k,int num )
{
     if( num < 0 )//右括号不能多于左括号
         return ;
     if( k == l )
     {
         if( num == 0 )//当左边跟右边的括号相等且刚好到最后一个,就是一中符合条件的可能
             ++cnt;
         return;
     }
     if( str[k] == '(' )
         DFS( k + 1,num + 1 );
     else if( str[k] == ')' )
         DFS( k + 1,num - 1 );
     else//?
     {
         DFS( k + 1,num + 1 );
         DFS( k + 1,num - 1 ); 
         }
 }
int main( )
{
    while( gets( str ) )
    {
           l = strlen( str );
           cnt = 0;
           DFS( 0,0 );
           printf( "%d\n",cnt );
           }
    return 0;
}

抱歉!评论已关闭.