View Code
#include
<
iostream
>
using namespace std;
char ch[ 101 ];
int mark = 0 , cnt;
int len;
void dfs( int x , int y , int i )
{
if ( x < y )
{ return ; }
if ( y == x && i == len )
{
cnt ++ ;
}
if (ch[i] == ' ? ' )
{
dfs(x + 1 , y , i + 1 );
dfs(x, y + 1 , i + 1 );
}
if (ch[i] == ' ( ' )
{
dfs( x + 1 , y , i + 1 );
}
if (ch[i] == ' ) ' )
{
dfs( x , y + 1 , i + 1 );
}
}
int main()
{
while (cin >> ch)
{
cnt = 0 ; len = strlen( ch );
dfs( 0 , 0 , 0 );
if (mark == 1 ) cout << " 0 " << endl;
else cout << cnt << endl;
}
return 0 ;
}
using namespace std;
char ch[ 101 ];
int mark = 0 , cnt;
int len;
void dfs( int x , int y , int i )
{
if ( x < y )
{ return ; }
if ( y == x && i == len )
{
cnt ++ ;
}
if (ch[i] == ' ? ' )
{
dfs(x + 1 , y , i + 1 );
dfs(x, y + 1 , i + 1 );
}
if (ch[i] == ' ( ' )
{
dfs( x + 1 , y , i + 1 );
}
if (ch[i] == ' ) ' )
{
dfs( x , y + 1 , i + 1 );
}
}
int main()
{
while (cin >> ch)
{
cnt = 0 ; len = strlen( ch );
dfs( 0 , 0 , 0 );
if (mark == 1 ) cout << " 0 " << endl;
else cout << cnt << endl;
}
return 0 ;
}
本文探讨了一个使用C++实现的括号匹配问题解决方案。通过深度优先搜索(DFS)算法,代码处理了由'?'、'('、')'组成的字符串,计算可能的有效括号组合数量。此算法对于理解递归和数据结构如栈有重要帮助。

642

被折叠的 条评论
为什么被折叠?



