CodingTrip - 携程编程大赛 (预赛第一场)第二题 括号匹配

本文详细解析了一段使用C++编写的代码片段,重点在于理解并实现一个递归函数dfs,用于解决括号匹配问题。通过定义辅助函数和使用多种数据结构如vector、queue等,展示了如何高效地解决此类问题。代码示例涵盖了字符串操作、数组和数据结构应用,适合对C++进阶编程技巧感兴趣的开发者。
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <sstream>
#include <set>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <bitset>

using namespace std;

#define rep(i, n) for(int i = 0; i < n; i++)
#define repf(i, a, b) for(int i = a; i <= b; i++)

#define PB push_back
#define MP make_pair
#define CC(a, b) memset(a, b, sizeof(a))
#define ALL(a) a.begin(), a.end()
#define SZ(a) ((int)a.size())
#define lowbit(x) ((x) & (-x))
#define foreach(it, a) for(__typeof((a).begin()) it=(a).begin(); it!=(a).end(); it++)
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
#define x first
#define y second

typedef long long LL;
typedef unsigned long long ULL;

const int inf = 0x7f7f7f7f;
const int maxn = 111;
const int mod = 1000000007;
const double eps = 1e-8;

char str[maxn];
int dp[maxn][maxn];

int dfs(int l, int r) {
    if(l == r) return 1;
    if(l > r) return 0;
    if(dp[l][r] != inf) return dp[l][r];
    if(str[l] == '(' && str[r] == ')' || str[l] == '[' && str[r] == ']') {
        dp[l][r] = dfs(l + 1, r - 1);
    }
    for(int i = l; i <= r; i++) {
        dp[l][r] = min(dp[l][r], dfs(l, i) + dfs(i + 1, r));
    }
    return dp[l][r];
}

int main() {
    int t; cin >> t;
    while(t--) {
        cin >> str;
        CC(dp, 0x7f);
        cout << dfs(0, strlen(str) - 1) << endl;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值